Convert NodeList to an Array
<!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);
//won't work in IE8 and earlier
var arrayOfNodes = Array.prototype.slice.call(resultsElement.childNodes,0);
document.writeln(arrayOfNodes.length);
</script>
</body>
</html>
To convert a NodeList to an array in Internet Explorer, you must manually iterate over the members.
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<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>
Home
JavaScript Book
DOM
JavaScript Book
DOM
DOM Model:
- Document Object Model
- nodeName and nodeValue Properties
- Node Relationships:childNodes
- parentNode
- previousSibling and nextSibling properties
- lastChild and firstChild
- appendChild() adds a node to the end of the childNodes list
- insertBefore()
- ownerDocument property
- removeChild
- replaceChild()
- Working with Text
- Check the length of NodeList
- Convert NodeList to an Array
- html tag and its cooresponding JavaScript class