childNodes

In this chapter you will learn:

  1. How to use childNodes to get node relationships
  2. How to get child node by index

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

null

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>

Click to view the demo

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>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. How to get the parent node in Javascript
Home » Javascript Tutorial » DOM
Document Object Model
Node Type
nodeName and nodeValue
childNodes
parentNode
previousSibling and nextSibling
lastChild and firstChild
appendChild
insertBefore
ownerDocument
removeChild
replaceChild
Text
NodeList Length
DOM classes