1. Computing

JavaScript By Example

Document Object Model: 8. Get Child Nodes

By

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.

HTML


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example D08</title>
</head>
<body>
<div>x</div>
<div>x</div>
<div id="me">x</div>
<div>x</div>
<div>x</div>
<div>x</div>
<script type="text/javascript" src="exampleD08.js"></script>
</body>
</html>

JavaScript


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';
}

  1. About.com
  2. Computing
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Document Object Model
  7. JavaScript By Example - DOM: Get Child Nodes

©2014 About.com. All rights reserved.