程式碼首行 if (!document.getElementById(id)) return; 旨在檢查元素是否存在,實則**多餘**。
| 方法 | 元素存在 | 元素不存在 |
|---|---|---|
document.getElementById(id) | 回傳 Element | 回傳 null (不拋錯) |
document.querySelector(selector) | 回傳 Element | 回傳 null |
document.getElementsByClassName(cls)[0] | 回傳 Element | 回傳 undefined (存取 [0]) |
const el = document.getElementById(id);
if (!el) return; // 這裡檢查才有意義
el.style.color = 'red'; // 後續安全使用
null,避免重複查詢 DOM。document.getElementById(id).style... 且元素不存在 → TypeError: Cannot read property 'style' of null。結論:**getElementById 找不到回傳 null,不會報錯;首行獨立檢查屬多餘,合併至變數宣告即可。**