What type of object is returned by this call? How do I access each item in this list? I would like to loop through the list and print each item.
Thanks!
I figured out my own answer. I can access the items in the list like this:
elements.item(i).tagName
The getElementsByTagName() method returns a collection (an array) of all the elements in the document. You can reference it like a normal array. Here is an example:
var els=document.getElementsByTagName("*");
for(var i=0;i<els.length;i+)
document.write(els.nodeName+"<br />");
Hope that helps!
Happy coding! :)
It returns a "NodeList" (defined in DOM1, DOM2, and DOM3 Core), which is basically an array with an additional "item" method where:
nodelist.item(X) == nodelist[X]
As a matter of fact, W3C never defined in their specs an array accessor to members of a NodeList, but all browsers which support DOM allow it anyway.
onload = function() {
var els;
if (document.all) els = document.all;
else els = document.getElementsByTagName('*');
viewer = open('','',
'width=120,height=500,left=100,top=10,scrollbars');
for (var i=0; els[i]; ++i)
viewer.document.write(els[i].nodeName + '<br />');
viewer.document.close();
}