- The entire document is a document node
- Every HTML element is an element node
- The text inside HTML elements are text nodes
- Every HTML attribute is an attribute node (deprecated)
- All comments are comment nodes
For example consider the following simple web page
<html>
<head>
<title>HTML DOM Demonstration</title>
</head>
<body>
<h1>Headings</h1>
<p>Hello world!</p>
</body>
</html>
From the HTML above you can read:
<html> is the root node
<html> has no parents
<html> is the parent of <head> and <body>
<head> is the first child of <html>
<body> is the last child of <html>
and:
<head> has one child: <title>
<title> has one child (a text node): "DOM Tutorial"
<body> has two children: <h1> and <p>
<h1> has one child: "DOM Lesson one"
<p> has one child: "Hello world!"
<h1> and <p> are siblings
In short an HTML document is composed of element nodes and JavaScript provides a very sophicated way to manipulate and access each and every node in the document.
JavaScript provides following simple functions and properties to navigate the DOM Elements
- parentNode
- childNodes[nodenumber]
- firstChild
- lastChild
- nextSibling
- previousSibling
- nodeName
- nodeType
- nodeValue
- document.documentElement
- document.body
<!DOCTYPE html>
<html>
<body>
<h1 id="id01">My First Page</h1>
<p id="id02">Hello!</p>
<p>Hello World!</p>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>document.documentElement</b> property.</p>
</div>
<script>
document.getElementById("id02").innerHTML = document.getElementById("id01").childNodes[0].nodeValue;
document.getElementById("id02").innerHTML = document.getElementById("id01").firstChild.nodeValue;
document.getElementById("id02").innerHTML = document.getElementById("id01").innerHTML;
document.getElementById("id02").innerHTML = document.getElementById("id01").nodeName;
document.getElementById("id02").innerHTML = document.getElementById("id01").nodeType;
alert(document.documentElement.innerHTML);
alert(document.body.innerHTML);
</script>
</body>
</html>
Below is the code screen and its output.
document.getElementById("id02").innerHTML = document.getElementById("id01").childNodes[0].nodeValue;
document.getElementById("id02").innerHTML = document.getElementById("id01").firstChild.nodeValue;
document.getElementById("id02").innerHTML = document.getElementById("id01").innerHTML;
document.getElementById("id02").innerHTML = document.getElementById("id01").nodeName;
document.getElementById("id02").innerHTML = document.getElementById("id01").nodeType;
alert(document.documentElement.innerHTML);
alert(document.body.innerHTML);
document.getElementById("id02").innerHTML give us the node text and it is similar to document.getElementById("id01").childNodes[0].nodeValue;
document.getElementById("id01").firstChild.nodeValue; From this code line it is clear that childNodes[0] and firstChide are similar takes us to first node in HTML dom