PPK on JavaScript: The DOM - Part 1/Page 3 | WebReference

PPK on JavaScript: The DOM - Part 1/Page 3

[previous] [next]

PPK on JavaScript: The DOM - Part 1

B: Finding elements

The first step in any DOM script is finding the elements you want to do something with. There are two ways of finding elements:

Long-distance travel

When you start up your script, you usually want to find some HTML elements somewhere in the document. The two methods getElementById() and getElementsByTagName(), which we've already seen in many code examples in the previous chapters, can find any HTML element in the entire document, provided you give them correct instructions.

These two methods largely ignore the document structure. If you want to find all <p>s in the document, it doesn't really matter if they're direct children of the <body> or children of <div>s or other elements; you just want to get them all. Similarly, getElementById() always returns the correct element, wherever it may be hidden in the document structure. Therefore, these two methods are the ones you need for "long-distance" searching: they give you the HTML elements you need regardless of where they are in the document.


The getElementById() method returns the element that has the ID specified in the argument:

Not in XML: getElementById() is the single W3C DOM method that doesn't always work in XML. In an XML document, it searches through attributes that have the type (and not the name!) id, and this type must be defined in the XML document's Document Type Definition (DTD).


The getElementsByTagName() method returns a nodeList (and not an array!) of all elements with the desired tag name that are descendants of the element on which you use the method. We'll discuss nodeLists in detail in 8I. Once we have a nodeList, we go through all elements in it and do something with them, for instance, checking if they have a certain attribute, or setting an event handler on them.

getElementsByTagName() can be used on any HTML element, as well as on the document. Both of these calls are therefore valid:

The first call returns a nodeList of all <p> elements in the document, while the second one returns a nodeList of all <p> elements that are descendants of the element with ID="someID".

We usually store such a nodeList in a variable:

Now pars contains a list of all individual <p>s in the page, and we can access them by their index numbers. The first <p> has index 0, the second index 1, etc. The most common use of getElementsByTagName() is requesting all tags of a certain type in order to loop through them.

To access the fifth <p> in the page you can also say:

This syntax is useful only if you know exactly which <p> you want to access, and are certain that it hasn't been moved or removed by another part of your script. Therefore it isn't often used.

[previous] [next]