This is how you access the <body>
element to set a background style:
document.body.style.background = '';
But how can I access the <html>
element in a similar manner? The following doesn't work:
document.html.style.background = '';
The easiest way to find an HTML element in the DOM, is by using the element id.
The DOM document Reference chapter describes the document object. Every object located within a document is a node of some kind. In an HTML document, an object can be an element node but also a text node or attribute node.
The getElementById Method The most common way to access an HTML element is to use the id of the element. In the example above the getElementById method used id="demo" to find the element.
<head> The <head> HTML element contains machine-readable information (metadata) about the document, like its title, scripts, and style sheets. <link> The <link> HTML element specifies relationships between the current document and an external resource.
The <html>
element can be referred through the document.documentElement
property. In general, the root element of any document can be referred through .documentElement
.
document.documentElement.style.background = '';
Note: .style.background
returns the value for background
as an inline style property. That is, defined using <html style="background:..">
. If you want to get the calculated style property, use getComputedStyle
:
var style = window.getComputedStyle(document.documentElement); var bgColor = style.backgroundColor;
The root element (<html>
) can be found in document.documentElement
, not document.html
.
This is because documentElement
is standard DOM and not an HTML specific extension.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With