In this tutorial, we use the innerHTML property to retrieve the content of an HTML element. However, learning the other methods mentioned above is valuable for understanding the tree structure and how to navigate the DOM.
There are two special properties that provide access to the entire document:
<html> <body> <h2>JavaScript HTMLDOM</h2> <p>Displaying document.body</p> <p id=”demo”></p> <script> document.getElementById(“demo”).innerHTML = document.body.innerHTML; </script> </body> </html> |
<html> <body> <h2>JavaScript HTMLDOM</h2> <p>Displaying document.documentElement</p> <p id=”demo”></p> <script> document.getElementById(“demo”).innerHTML = document.documentElement.innerHTML; </script> </body> </html> |
The nodeName property specifies the name of a node:
nodeName is read-only.
<h1 id=”id01″>My First Page</h1> <p id=”id02″></p> <script> document.getElementById(“id02”).innerHTML = document.getElementById(“id01”).nodeName; </script> |
Note: The nodeName property always contains the tag name of an HTML element in uppercase. |
The nodeValue property specifies the value of a node:
The nodeType property is read-only and returns the type of a node.
<h1 id=”id01″>My First Page</h1> <p id=”id02″></p> <script> document.getElementById(“id02”).innerHTML = document.getElementById(“id01”).nodeType; </script> |
The key nodeType properties are:
Node |
Type |
Example |
ELEMENT_NODE |
1 |
<h1 class=”heading”>W3Schools</h1> |
ATTRIBUTE_NODE |
2 |
class = “heading” (deprecated) |
TEXT_NODE |
3 |
W3Schools |
COMMENT_NODE |
8 |
<!– This is a comment –> |
DOCUMENT_NODE |
9 |
The HTML document itself (the parent of <html>) |
DOCUMENT_TYPE_NODE |
10 |
<!Doctype html> |