↑
Main Page
Accessing specific nodes
Accessing specific nodes
You already know how to access parent and child nodes, but what if you want access to a node (or
group of nodes) that are located deep in the document? Certainly, you don’t want to count child nodes
until you get down to what you’re looking for. To help you in this use case, the DOM provides several
methods to enable easy access to specific nodes.
getElementsByTagName()
The Core (XML) DOM defines the method
getElementsByTagName()
to return a
NodeList
of all
Element
objects whose
tagName
property is equal to a specific value. In an
Element
object, the
tagName
property is always equal to the name immediately following the less-than symbol — for
example, the
tagName
of
<img />
is
“img”
. The following line of code returns a list of all
<img />
elements in a document:
var oImgs = document.getElementsByTagName(“img”);
After storing all of the images in
oImgs
, you can access them individually in the same way that you access
child nodes, by using either square-bracket notation or the
item()
method (
getElementsByTagName()
returns a
NodeList
, just like
childNodes
):
alert(oImgs[0].tagName); //outputs “IMG”
This line of code outputs the
tagName
of the first image, which is output as
“IMG”
. For some reason,
most browsers still record the tag name as all uppercase even though XHTML conventions dictate that
tag names must be all lowercase.
But suppose you want to get only the images within the first paragraph of a page. This can be accom-
plished by calling
getElementsByTagName()
on the first paragraph element, like this:
var oPs = document.getElementsByTagname(“p”);
var oImgsInP = oPs[0].getElementsByTagName(“img”);
You can use this one method to get down to any element in the
document
or to get all elements in the
document
by using an asterisk:
var oAllElements = document.getElementsByTagName(“*”);
This line of code returns all the elements contained in
document
regardless of their tag names.
getElementsByName()
The HTML DOM defines
getElementsByName()
to retrieve all elements that have their
name
attribute
set to a specific value. Consider the following HTML:
Internet Explorer 6.0 doesn’t return all elements when the argument is an asterisk.
You must use
document.all
instead.
171
DOM Basics
09_579088 ch06.qxd 3/28/05 11:37 AM Page 171
Free JavaScript Editor
Ajax Editor
©
→