NodeList Length

In this chapter you will learn:

  1. How to get the length of a NodeList
  2. How to Convert NodeList to an Array
  3. Convert a NodeList to an array in Internet Explorer

Check the length of NodeList

The following code checks the length of a NodeList for a div element.

<!DOCTYPE HTML> <!--from  j  ava 2  s. com-->
<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 count = resultsElement.childNodes.length; 
    document.writeln(count); 
    
    
  </script>  
</body> 
</html>

Click to view the demo

Convert NodeList to an Array

The following code converts NodeList to an Array with slice method from Array class.

<!DOCTYPE HTML> <!--from   j a va 2  s.  c  om-->
<html> 
<body> 
    <div id="results">
       <code><code>
       <p></p>
    </div> 
    <script> 
    var resultsElement = document.getElementById("results"); 
    document.writeln(resultsElement.nodeType); 
    document.writeln(resultsElement.nodeName); 
    
    //won't work in IE8 and earlier 
    var arrayOfNodes = 
           Array.prototype.slice.call(resultsElement.childNodes,0); 
    document.writeln(arrayOfNodes.length); 
    </script>  
</body> 
</html>

Click to view the demo

Convert a NodeList to an array in Internet Explorer

To convert a NodeList to an array in Internet Explorer, you must manually iterate over the members.

<!DOCTYPE HTML> <!--   ja  va 2s .c  o  m-->
<html> 
<body> 
    <div id="results">
       <code><code>
       <p></p>
    </div> 
    <script> 
    function convertToArray(nodes){ 
        var array = null; 
        try {
             array = Array.prototype.slice.call(nodes, 0); 
             //non-IE and IE9+
        } catch (ex) { 
            array = new Array(); 
            for (var i=0, len=nodes.length; i < len; i++){
                array.push(nodes[i]); 
            } 
        }
        return array; 
    }    
    var resultsElement = document.getElementById("results"); 
    document.writeln(resultsElement.nodeType); 
    document.writeln(resultsElement.nodeName); 
    
    var arrayOfNodes = convertToArray(resultsElement.childNodes); 
    document.writeln(arrayOfNodes.length); 
    </script>  
</body> 
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. Class list for HTML DOM
  2. Classes for grouping element
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