Node Relationships:childNodes

All nodes in a document have relationships to other nodes.

For the following html code:

 
<html>
    <head>
        <title>Sample Page</title>
    </head>
    <body>
        <p id='myP'>Hello World!</p>
    </body>
</html>
  

Its DOM tree is

domModel.png

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> 
<html> 
    <head> 
        <title>Example</title> 

    </head> 
    <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

By item

 
<!DOCTYPE HTML> 
<html> 
    <head> 
        <title>Example</title> 
    </head> 

    
    <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
Home 
  JavaScript Book 
    DOM  

DOM Model:
  1. Document Object Model
  2. nodeName and nodeValue Properties
  3. Node Relationships:childNodes
  4. parentNode
  5. previousSibling and nextSibling properties
  6. lastChild and firstChild
  7. appendChild() adds a node to the end of the childNodes list
  8. insertBefore()
  9. ownerDocument property
  10. removeChild
  11. replaceChild()
  12. Working with Text
  13. Check the length of NodeList
  14. Convert NodeList to an Array
  15. html tag and its cooresponding JavaScript class