核心概念
-
定义
- 它始终指向当前文档的根元素,在 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
更高效。