Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reference the <HTML> element's corresponding DOM object?

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 = ''; 
like image 694
tkane Avatar asked Feb 20 '12 14:02

tkane


People also ask

How do I find the HTML element of a DOM?

The easiest way to find an HTML element in the DOM, is by using the element id.

What is HTML DOM reference?

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.

Which DOM methods are used to access HTML elements?

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.

What is element reference in HTML?

<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.


2 Answers

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; 
like image 123
Rob W Avatar answered Sep 22 '22 08:09

Rob W


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.

like image 37
Quentin Avatar answered Sep 22 '22 08:09

Quentin