From http://www.w3schools.com (Copyright Refsnes Data)
With the DOM, you can access every node in an HTML document.
You can access a node in three ways:
1. By using the getElementById() method
2. By using the getElementsByTagName() method
3. By navigating the node tree, using the node relationships.
The getElementById() method returns the element with the specified ID:
document.getElementById("someID"); |
Note: The getElementById() method doesn't work in XML.
getElementsByTagName() returns all elements with a specified tag name.
node.getElementsByTagName("tagname"); |
The following example returns a nodeList of all <p> elements in the document:
document.getElementsByTagName("p"); |
The following example returns a nodeList of all <p> elements that are descendants of the element with id="main":
document.getElementById('main').getElementsByTagName("p"); |
The getElementsByTagName() method returns a node list. A node list is an array of nodes.
The following code stores a list of <p> nodes (a node list) in the variable x:
x=document.getElementsByTagName("p"); |
The <p> elements in x can be accessed by index number. To access the second <p> you can write:
y=x[1]; |
Note: The index starts at 0.
You will learn more about node lists in a later chapter of this tutorial.
The length property defines the length of a node list (the number of nodes).
You can loop through a node list by using the length property:
x=document.getElementsByTagName("p"); for (i=0;i<x.length;i++) { document.write(x[i].innerHTML); document.write("<br />"); } |
Example explained:
The three properties parentNode, firstChild, and lastChild follow the document structure and allow short-distance travel in the document.
Look at the following HTML fragment:
<html> <body> <p id="intro">W3Schools example</p> <div id="main"> <p id="main1">The DOM is very useful</p> <p id="main2">This example demonstrates <b>node relationships</b></p> </div> </body> </html> |
In the HTML code above, the <p id="intro"> is the first child node (firstChild) of the <body> element, and the <div> element is the last child node (lastChild) of the <body> element.
Furthermore, the <body> is the parent (parentNode) of the every <p> element.
The firstChild property can be used to access the text of an element:
var x=document.getElementById("intro"); |
There are two special document properties that allow access to the tags:
The first property returns the root node of the document and exists in all XML and HTML documents.
The second property is a special addition for HTML pages, and gives direct access to the <body> tag.
From http://www.w3schools.com (Copyright Refsnes Data)