本頁只練什麼
能處理 querySelectorAll 的 NodeList,並在單一 selector 找不到時安全停止。
把 NodeList 當單一元素或對 null 讀 property,會讓整段 render 在第一個缺少節點時中止。
要修改的檔案:files/starter/main.js
定位:先輸出 selector 結果與 NodeList.length。|依 starter-1 定位,只修改「querySelectorAll() 與 null guard」的責任。
LESSON-16 · TOPIC 01
能處理 querySelectorAll 的 NodeList,並在單一 selector 找不到時安全停止。
能處理 querySelectorAll 的 NodeList,並在單一 selector 找不到時安全停止。
把 NodeList 當單一元素或對 null 讀 property,會讓整段 render 在第一個缺少節點時中止。
要修改的檔案:files/starter/main.js
定位:先輸出 selector 結果與 NodeList.length。|依 starter-1 定位,只修改「querySelectorAll() 與 null guard」的責任。
先結果,再原理;完成後要能說出自己看見的證據。
共用 main.js 在沒有 status 的頁面整段白畫面。
起始狀態:程式直接對 missing selector 讀 textContent。
itemCount=3、missing=true、guarded=true、uncaught=0。
驗收證據:itemCount=3、missing=true、guarded=true
批次卡片、導覽連結與不是每頁都有的可選元件。
常見混淆:空 NodeList 不是 null,仍可 forEach;querySelector 才可能直接回 null。
這段程式是理解起點,不是要你直接跳過 Starter。
找多個先看有幾個;找一個可能找不到,先確認不是 null。
正式說法:querySelectorAll 回傳靜態 NodeList;querySelector 無匹配時回傳 null,存取前需控制流程縮小型別。
const status=document.querySelector('#status'); if (!status) return。每一步都留下可觀察結果;如果沒看到,先看「卡住先查」。
檔案:files/starter/main.js 定位:先輸出 selector 結果與 NodeList.length。
要做:先重新載入 Starter,記錄目前畫面、DOM、Computed、Console 或文件內容。
預期:能指出「先輸出 selector 結果與 NodeList.length。」目前的缺口。
證據:保存 files/starter/main.js 的目前狀態,並指出下一步只會修改哪個檔案責任。
卡住先查:確認開啟的是 files/starter/main.js,且定位到 先輸出 selector 結果與 NodeList.length。。
檔案:files/starter/main.js 定位:先輸出 selector 結果與 NodeList.length。
要做:查三個 items 與缺少的 status,以 guard 記錄安全分支。
預期:itemCount=3、missing=true、guarded=true、uncaught=0。
證據:itemCount=3、missing=true、guarded=true
卡住先查:先輸出 selector 結果與 NodeList.length。
檔案:files/starter/main.js 定位:先輸出 selector 結果與 NodeList.length。
要做:重新整理頁面,再逐項比對預期結果與 evidence。
預期:itemCount=3、missing=true、guarded=true、uncaught=0。
證據:itemCount=3、missing=true、guarded=true
卡住先查:先輸出 selector 結果與 NodeList.length。
這個示範只讓你看懂概念,不會替你修改 Starter,也不會自動宣告完成。
勾選只是學習紀錄;真正完成仍要回到 Starter 的實際結果。
多個結果看 length;單一結果和 null 比較。
在讀 property 前先 if (!status) return。
完整解答與原因:querySelectorAll 取得三個 item;querySelector 缺少 status 得 null,先 guard 後不再存取它,因此沒有 TypeError。