In the DOM terminology, an HTMLCollection
is a set of DOM nodes that behave in a way that lets developers think that they're dealing with a normal array. This is not the case, because this kind of DOM structure shares only the length
property and the indexed access to elements with a normal JavaScript array object. Sometimes, however, it's preferable to turn this kind of collection into a normal JavaScript array, for example to use some of the most popular array methods. Here's an example:
function HTMLNodesToArray(reference, elems) { reference = document.getElementById(reference); elems = elems || '*'; var nodes = []; var elements = reference.getElementsByTagName(elems); var i; var len = elements.length; for(i = 0; i< len; i += 1) { var node = elements[i]; nodes.push(node); } return nodes; }
This function simply iterates over an HTMLCollection
and stores all its member nodes in an array for later use. A practical example would be the following:
unction showNodes() { var htmlNodes = HTMLNodesToArray('test', 'li'); var reduced = htmlNodes.pop(); var last = reduced; alert(last.firstChild.nodeValue); } window.onload = function() { showNodes(); };
In this case, we've been able to use the common array pop()
method on our collection of nodes.