萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

深入解析 JavaScript document 物件核心屬性集合與實戰應用

document 物件核心集合屬性一覽

屬性回傳型別說明現代替代方案
document.formsHTMLCollection頁面所有 <form> 元素document.querySelectorAll('form')
document.anchorsHTMLCollection所有有 name 屬性的 <a> (HTML5 廢棄,改用 id)document.querySelectorAll('a[name]')
document.linksHTMLCollection所有有 href 屬性的 <a> 與 <area>document.querySelectorAll('a[href], area[href]')
document.imagesHTMLCollection所有 <img> 元素document.querySelectorAll('img')
document.scriptsHTMLCollection所有 <script> 元素document.querySelectorAll('script')
document.appletsHTMLCollection所有 <applet> (已淘汰)不建議使用
document.allHTMLAllCollection文檔中所有元素 (非標準、IE 專屬遺產)document.querySelectorAll('*')
document.styleSheetsStyleSheetList所有樣式表 (含 <link rel=stylesheet>、<style>)同左 (標準 API)
document.bodyHTMLElement<body> 元素同左
document.titlestring文檔標題 (可讀寫)同左
document.headHTMLHeadElement<head> 元素 (HTML5 新增)同左
document.documentElementHTMLElement<html> 根元素同左
document.activeElementElement目前取得焦點的元素同左
document.readyStatestringloading、interactive、complete同左
document.referrerstring來源頁面 URL同左
document.cookiestringCookie 字串讀寫同左
document.domainstring文檔域 (可設定放寬同源策略)同左
document.lastModifiedstring文檔最後修改時間同左
document.URL / document.locationstring / 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 定位錨點。
copyright © 萬盛學電腦網 all rights reserved