352
Chapter 6
So far, you’ve been using getElementById()
to nd a specic element in an HTML DOM
tree. But there’s another useful method called
getElementsByTagName(). You can use
this to nd all the elements in a DOM tree with a
certain name, like this:
I’m with you so far, but how can we get
to those three “sold” elements in the
XML? They don’t have id attributes like
the <span> elements in Katie’s HTML.
You can nd them with their “tag name”
var xmlDoc = request.responseXML;
var boardsSoldElements =
xmlDoc.getElementsByTagName(“boards-sold”);
This will return an array of all the elements
named “boards-sold” in the xmlDoc DOM tree.
Then, you can get elements from the list using an
index, like this:
var rstBoardsSoldElement =
boardsSoldElements[0];
Remember, JavaScript
arrays start at 0, not 1.
You could also loop through
this list using a “for” loop,
if you wanted to.
var rstBoardsSoldElement = xmlDoc.getElementsByTagName(“boards-sold”)[0];
Time to take a shortcut:
This gets all the elements
named “boards-sold”...
...and this returns just the
rst element from the list.
Get the DOM tree
representing the
server’s XML request.
Now we’re working
with the DOM!
working with xml using the dom