LESSON-16 · TOPIC 01

querySelectorAll() 與 null guard

能處理 querySelectorAll 的 NodeList,並在單一 selector 找不到時安全停止。

code-edit安全 DOM 查找與可重複渲染|querySelectorAll() 與 null guard本頁只練一個責任

本頁只練什麼

能處理 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。

querySelectorAll() 與 null guard Multiple-element query and null guard

找多個先看有幾個;找一個可能找不到,先確認不是 null。

正式說法:querySelectorAll 回傳靜態 NodeList;querySelector 無匹配時回傳 null,存取前需控制流程縮小型別。

const status=document.querySelector('#status'); if (!status) return。

三步完成本主題

每一步都留下可觀察結果;如果沒看到,先看「卡住先查」。

  1. Step 1|先看見目前缺口,不急著貼答案。

    檔案: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。。

  2. Step 2|只修改本主題的一個責任。

    檔案: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。

  3. Step 3|重新載入並以證據驗收,不以『看起來差不多』判定完成。

    檔案: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,也不會自動宣告完成。

querySelectorAll() 與 null guardruntime fixture · read-only demo
本主題示範畫面:
A
B
C

驗收證據

勾選只是學習紀錄;真正完成仍要回到 Starter 的實際結果。

提示 1|方向

多個結果看 length;單一結果和 null 比較。

提示 2|關鍵片段

在讀 property 前先 if (!status) return。

提示 3|完整解答與原因

完整解答與原因:querySelectorAll 取得三個 item;querySelector 缺少 status 得 null,先 guard 後不再存取它,因此沒有 TypeError。

完成後進入下一階段,或回到入口選下一個 topic。

開始 Starter →回到主題清單