Another Useful JavaScript DOM Property
You will no doubt recall that we described some of these methods in Lesson 6, "A Brief Introduction to XML." Let's now examine one more of these methods, namely getElementsByTagName().
The getElementsByTagName() Method
This useful method allows you to build a JavaScript array of all the elements having a particular tagname. You can then access elements of that array using normal JavaScript statements. Here's an example:
var myElements = object.getElementsByTagName('greeting');
This line creates the array myElements and populates it with all the elements with tagname greeting. As with any other array, you can find out the length of the array (that is, the number of elements having the declared tagname) by using the length property:
myElements.length
You can access a particular element individually if you want; the first occurring element with tagname greeting can be accessed as myElements[0], the second (if there is a second) as myElements[1], and so:
var theElement = myElements[0];
Tip
![]() | You could also access these individual array elements directly: var theElement = object.getElementsByTagName('greeting')[0]; |