HTML and CSS Reference
In-Depth Information
Now that you have successfully obtained a reference to your <div> , you can do anything
you want to it dynamically—just as you could have defined or applied such changes to it
statically. The getElementById method is great when you know the ID of a specific element in
the page that you want to work with, but in other cases you might want to do something to
all the elements of a particular type—for example, all paragraph elements. In this case, the
getElementsByTagName method is more appropriate. You can use the following code to get a
reference to all the <p> elements:
<script>
window.onload = function () {
var paragraphs = document.getElementsByTagName("p");
alert(paragraphs.length);
}
</script>
In this code, the object returned from the getElementsByTagName method is a little differ-
ent; it's a special type that acts as a wrapper to all the elements that match your parameter,
called a NodeList . This object isn't especially useful by itself. In fact, it doesn't really provide
anything useful other than a length, which lets you know how many items it contains, and the
ability to access each individual item. In the preceding example, the JavaScript alert displays
how many items were returned in the list ( paragraphs.length ). You can see that the method
returned all five of the <p> elements in the page, as shown in Figure 1-15.
FIGURE 1-15 A message showing the number of <p> elements
In the same way that you could use the getElementsByTagName method to get all
elements of the same type, you can use the getElementsByClassName method to get all
elements of the same CSS class. This is useful when you have many elements with the same
style but perhaps want to modify them at run time. This method also returns a NodeList . The
following snippet demonstrates the usage:
<script>
window.onload = function () {
var paragraphs = document.getElementsByClassName("subPara");
alert("<p> elements with class subPara: " + paragraphs.length);
}
</script>
Figure 1-16 shows the output of this script.
 
Search WWH ::




Custom Search