NodeList Length
In this chapter you will learn:
- How to get the length of a NodeList
- How to Convert NodeList to an Array
- 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>
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>
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>
Next chapter...
What you will learn in the next chapter: