childNodes
In this chapter you will learn:
childNodes tells Node relationships
All nodes in a document have relationships to other nodes.
For the following html code:
Hello World!
Its DOM tree is
In HTML, the <body>
element
is considered a child of the <html>
element.
The <html>
element is considered the
parent of the <body>
element.
The <head>
element is considered
a sibling of the <body>
element.
Each node has a childNodes
property containing a NodeList.
A NodeList
is an array-like object used to store an ordered
list of nodes that are accessible by position.
The following example shows how nodes stored in a NodeList
may be accessed via bracket notation
or by using the item()
method:
<!DOCTYPE HTML> <!--from j a v a 2 s. co m-->
<html>
<body>
<pre id="results"><code><code></pre>
<script>
var resultsElement = document.getElementById("results");
document.writeln(resultsElement.nodeType);
document.writeln(resultsElement.nodeName);
var firstChild = resultsElement.childNodes[0];
document.writeln(firstChild.nodeName);
</script>
</body>
</html>
Get child node by index
The following Javascript code gets the reference of a div
element by its id.
And then it uses the index to get its child at specific position.
<!DOCTYPE HTML> <!-- j a va 2s . co m-->
<html>
<body>
<div id="results">
<code><code>
<p></p>
</div>
<script>
var resultsElement = document.getElementById("results");
document.writeln(resultsElement.nodeType);
document.writeln(resultsElement.nodeName);
var secondChild = resultsElement.childNodes.item(1);
document.writeln(secondChild.nodeName);
</script>
</body>
</html>
Next chapter...
What you will learn in the next chapter: