document 物件核心集合屬性一覽
| 屬性 | 回傳型別 | 說明 | 現代替代方案 |
document.forms | HTMLCollection | 頁面所有 <form> 元素 | document.querySelectorAll('form') |
document.anchors | HTMLCollection | 所有有 name 屬性的 <a> (HTML5 廢棄,改用 id) | document.querySelectorAll('a[name]') |
document.links | HTMLCollection | 所有有 href 屬性的 <a> 與 <area> | document.querySelectorAll('a[href], area[href]') |
document.images | HTMLCollection | 所有 <img> 元素 | document.querySelectorAll('img') |
document.scripts | HTMLCollection | 所有 <script> 元素 | document.querySelectorAll('script') |
document.applets | HTMLCollection | 所有 <applet> (已淘汰) | 不建議使用 |
document.all | HTMLAllCollection | 文檔中所有元素 (非標準、IE 專屬遺產) | document.querySelectorAll('*') |
document.styleSheets | StyleSheetList | 所有樣式表 (含 <link rel=stylesheet>、<style>) | 同左 (標準 API) |
document.body | HTMLElement | <body> 元素 | 同左 |
document.title | string | 文檔標題 (可讀寫) | 同左 |
document.head | HTMLHeadElement | <head> 元素 (HTML5 新增) | 同左 |
document.documentElement | HTMLElement | <html> 根元素 | 同左 |
document.activeElement | Element | 目前取得焦點的元素 | 同左 |
document.readyState | string | loading、interactive、complete | 同左 |
document.referrer | string | 來源頁面 URL | 同左 |
document.cookie | string | Cookie 字串讀寫 | 同左 |
document.domain | string | 文檔域 (可設定放寬同源策略) | 同左 |
document.lastModified | string | 文檔最後修改時間 | 同左 |
document.URL / document.location | string / Location | 文檔 URL (location 可導航) | 同左 |
存取集合元素的三種方式
// 1. 索引存取
document.images[0]; // 第一張圖片
document.forms.item(0); // 同左
// 2. ID/Name 存取 (HTMLCollection 特有)
document.images['logo']; // id="logo" 或 name="logo" 的圖片
document.forms.loginForm; // name="loginForm" 的表單
// 3. namedItem (標準方法)
document.images.namedItem('logo');
實戰應用範例
1. 批次檢查圖片載入狀態
function checkImagesLoaded() {
var imgs = document.images;
var loaded = 0, total = imgs.length;
for (var i = 0; i < total; i++) {
if (imgs[i].complete && imgs[i].naturalWidth !== 0) loaded++;
}
console.log(`圖片載入: ${loaded}/${total}`);
return loaded === total;
}
2. 動態切換所有樣式表啟用狀態
function toggleStylesheets(enable) {
var sheets = document.styleSheets;
for (var i = 0; i < sheets.length; i++) {
sheets[i].disabled = !enable;
}
}
3. 表單驗證自動綁定
function autoValidateForms() {
var forms = document.forms;
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(e) {
if (!this.checkValidity()) {
e.preventDefault();
this.reportValidity(); // 瀏覽器原生提示
}
});
}
}
現代選擇器 API 取代集合屬性的優勢
- 靜態快照:
querySelectorAll 回傳靜態 NodeList,不受 DOM 變動影響;HTMLCollection 是即時的,迴圈中修改 DOM 易出錯。
- 彈性選擇:CSS 選擇器支援屬性、偽類、組合器,遠超集合屬性的固定篩選。
- 效能:現代瀏覽器
querySelectorAll 高度優化,差異可忽略。
兼容性提醒
document.head、document.activeElement、document.readyState:IE9+ 完整支援。
document.all:僅為相容舊代碼保留,**新代碼嚴禁使用**。
document.anchors:HTML5 標準已移除,改用 id 定位錨點。