在瀏覽器中,擁有 id 屬性的元素會自動成為 window 的屬性(非標準但廣泛實現):
<div id="myDiv">Hello</div>
<script>
console.log(myDiv === document.getElementById('myDiv')); // true
console.log(window.myDiv === myDiv); // true
</script>
HTML 標準規定:window[name] 返回名為 name 的元素集合(優先 id,其次 name)。但:
HTMLCollection(類數組)form, img, iframe, embed, object, applet, map, meta 等<form name="loginForm"></form>
<img name="banner" src="...">
<iframe name="mainFrame"></iframe>
console.log(loginForm); // HTMLFormElement
console.log(banner); // HTMLImageElement
console.log(mainFrame); // HTMLIFrameElement (可用於 target="mainFrame")
// 重複 name
<img name="pic" src="1.jpg">
<img name="pic" src="2.jpg">
console.log(pic); // HTMLCollection [img, img]
console.log(pic[0], pic[1]); // 可索引訪問
id="length" 會覆蓋 window.length(框架數量),導致難以調試的 Bug。var myDiv = ... 會遮蔽同名元素引用。window.myDiv = null 拋出錯誤。// 推薦:明確意圖、可壓縮、可分析、無副作用
const myDiv = document.getElementById('myDiv');
const forms = document.getElementsByName('loginForm'); // 返回 HTMLCollection
const imgs = document.querySelectorAll('[name="pic"]'); // 返回靜態 NodeList,推薦
// 現代選擇器 API(推薦)
const el = document.querySelector('#myDiv'); // 單個
const els = document.querySelectorAll('.my-class'); // 多個
const form = document.forms.loginForm; // 專用 form 集合
const img = document.images.banner; // 專用 img 集合
IE 專有,返回文檔中所有元素集合。現代瀏覽器為兼容保留但不推薦使用。判斷 IE 曾用 !!document.all,現已不可靠。
雖然瀏覽器自動將 id/name 映射為全局變量,**絕不應在生產代碼中依賴此特性**。始終使用 document.getElementById、querySelector、document.forms/name 等顯式 API,代碼更健壯、可維護、可優化。