JavaScript By Example

Document Object Model: 8. Get Child Nodes

Jupiterimages/Stockbyte/Getty Images

The opposite of getting the parent of the current node is to get the children of the current node. Since a node can have more than one child node within it the childNodes property is actually a nodelist rather than an individual node and so we will need a loop if we want to process them all.

While some things applied to a parent node will affect all of the child nodes within it (such as changing the background colour when the child nodes are going to inherit that colour) there are other things where we will need to loop through all of the child nodes applying the changes separately to each if we want that change to apply to everything within the parent.

For the purpose of this example we will update the text within each node at the same level in the document as the one with id="me" provided that they are not text nodes or script tag nodes.


<title>Example D08</title>
<div id="me">x</div>
<script type="text/javascript" src="exampleD08.js"></script>


var node;
node = document.getElementById('me').parentNode..childNodes;
for (var i = 0, ii = node.length; i < ii; i++)
  if (3 !== node[i].nodeType && 'SCRIPT' !== node[i].nodeName)
    node[i].innerHTML += 'child';