如何引用<HTML>元素的相应DOM对象?

tka*_*ane 21 html javascript

这是您访问<body>元素以设置背景样式的方法:

document.body.style.background = '';
Run Code Online (Sandbox Code Playgroud)

但是我怎样才能<html>以类似的方式访问元素呢?以下不起作用:

document.html.style.background = '';
Run Code Online (Sandbox Code Playgroud)

Rob*_*b W 32

所述<html>元件可以通过被称为document.documentElement属性.通常,可以引用任何文档的根元素.documentElement.

document.documentElement.style.background = '';
Run Code Online (Sandbox Code Playgroud)

注:.style.background返回值background作为内联样式属性.也就是说,定义使用<html style="background:..">.如果要获取计算出的样式属性,请使用getComputedStyle:

var style = window.getComputedStyle(document.documentElement);
var bgColor = style.backgroundColor;
Run Code Online (Sandbox Code Playgroud)

  • 可能是因为所有文档(XML,SVG,HTML,...)都有一个根,而"html"对于(X)HTML文档非常具体. (2认同)

Que*_*tin 5

根元素(<html>)可以找到document.documentElement,而不是document.html.

这是因为documentElement是标准DOM而不是HTML特定扩展.