JavaScript: Return a List of Elements for a Tag Name – getElementsByTagName

The document getElementsByTagName method returns a list of elements with a given tag name. getElementsByTagName is often used in Ajax applications and it’s usage was demonstrated in the series of articles I wrote on Ajax. One example included:

colors = objXHR.responseXML.getElementsByTagName('color');
for (i=0;i<colors.length;i++)
document.write(colors[i].firstChild.nodeValue);

This code retrieved all elements that were named color in the responseXML. The nodeValue of each of these elements was then accessed to get the color label.

getElementsByTagName is also often used as part of the Document Object Model to retrieve a list of nodes containing the information belonging to a tag. For instance:

var nodeList = document.getElementsByTagName('div');

The nodeList variable can then be traversed to examine or set properties on the div elements of a document as needed.

for(var i=0;i<nodeList.length;i++)
document.write(nodeList[i].style.fontWeight);

The preceding example simply outputs what the fontWeight CSS property is for each of the div elements in a document.

Leave a Reply