核心概念
-
定義
- 它始終指向當前文檔的根元素,在 HTML 文檔中對應
<html>
標簽。 - 與
document.body
(對應<body>
)和document.head
(對應<head>
)形成層級關系。
- 它始終指向當前文檔的根元素,在 HTML 文檔中對應
-
與
document.body
的區別<html> <!-- document.documentElement --><head> <!-- document.head --></head><body> <!-- document.body --></body> </html>
常見用途
1. 操作根元素樣式
// 修改根元素背景色
document.documentElement.style.backgroundColor = "#f0f0f0";// 添加 CSS 類名
document.documentElement.classList.add("dark-mode");
2. 獲取文檔尺寸
// 獲取視口寬度(兼容性寫法)
const width = document.documentElement.clientWidth;// 獲取整個文檔高度(包括滾動區域)
const height = document.documentElement.scrollHeight;
3. 動態主題切換
// 通過 CSS 變量定義主題
document.documentElement.style.setProperty("--primary-color", "#ff5722");
注意事項
-
兼容性
- 現代瀏覽器均支持,但在舊版 IE 中需注意:
- IE6-8 使用
document.documentElement
獲取視口尺寸。 - 其他瀏覽器可能使用
document.body
。
- IE6-8 使用
- 現代瀏覽器均支持,但在舊版 IE 中需注意:
-
XML 文檔
- 在非 HTML 文檔(如 XML)中,
document.documentElement
指向 XML 的根元素。
- 在非 HTML 文檔(如 XML)中,
-
與
window.document
的區別window.document
是文檔對象,而document.documentElement
是具體的 DOM 元素。
代碼示例
// 獲取根元素
const rootElement = document.documentElement;// 修改根元素屬性
rootElement.setAttribute("lang", "en");// 監聽根元素尺寸變化(需配合 ResizeObserver)
const observer = new ResizeObserver(entries => {console.log("文檔尺寸變化:", entries[0].contentRect);
});
observer.observe(rootElement);
總結
- 核心作用:直接操作 HTML 根元素,控制全局樣式或獲取文檔級信息。
- 典型場景:主題切換、響應式布局、動態樣式注入。
- 替代方案:部分操作可用
document.querySelector("html")
實現,但document.documentElement
更高效。