http://www.brainjar.com/dhtml/intro/default3.asp
Nodes
The Node
object provides several properties to reflect this structure and allow you to traverse the tree. Here are some relationships using the example above:
- NodeA
.firstChild
= NodeA1
- NodeA
.lastChild
= NodeA3
- NodeA
.childNodes.length
= 3
- NodeA
.childNodes[0]
= NodeA1
- NodeA
.childNodes[1]
= NodeA2
- NodeA
.childNodes[2]
= NodeA3
- NodeA1
.parentNode
= NodeA
- NodeA1
.nextSibling
= NodeA2
- NodeA3
.prevSibling
= NodeA2
- NodeA3
.nextSibling
= null
- NodeA
.lastChild.firstChild
= NodeA3a
- NodeA3b
.parentNode.parentNode
= NodeA
The Node
interface also provides methods for dynamically adding, updating and removing nodes such as:
insertBefore()
replaceChild()
removeChild()
appendChild()
cloneNode()
This interface provides methods for accessing and creating other nodes in the document tree. Some methods are:
getElementById()
getElementsByTagName()
createElement()
createAttribute()
createTextNode()
Traversing the Document Tree
Consider the following:
<html>
<head>
<title></title>
</head>
<body><p>This is a sample paragraph.</p></body>
</html>
and this code:
alert(document.documentElement.lastChild.firstChild.tagName);
which would display "P", the name of the tag represented by that node. The code breaks down as follows:
document.documentElement
- gives the page's HTML tag.
.lastChild
- gives the BODY tag.
.firstChild
- gives the first element in the BODY.
.tagName
- gives that element's tag name, "P" in this case.
Accessing Elements Directly
<p id="myParagraph">This is a sample paragraph.</p>
...
alert(document.getElementById("myParagraph").tagName);
-----------------
var nodeList = document.getElementsByTagName("A");
for (var i = 0; i < nodeList.length; i++)
nodeList[i].style.color = "#ff0000";
Attributes
<p id="sample1" align="left">Text in a paragraph element.</p>
... code for the links ...
document.getElementById('sample1').setAttribute('align', 'left');
document.getElementById('sample1').setAttribute('align', 'right');
Text Nodes
<p id="sample1">This is the initial text.</p>
... code for the links ...
document.getElementById('sample1').firstChild.nodeValue =
'Once upon a time...';
document.getElementById('sample1').firstChild.nodeValue =
'...in a galaxy far, far away';
--------------------------
<p id="sample2">This is the <b>initial</b> text.</p>