HTML and CSS Reference
In-Depth Information
the collection has an index number of 0. For example, if the first inline image within a
document has the tag
<img src=”logo.jpg” id=”logoImg” />
you can reference that image using any of the following expressions:
To avoid long object references in your code, you can store those references in variables.
The statement
var firstImg = document.images[0];
stores the object reference to the first inline image in the variable firstImg .
Like arrays, object collections support the length property. Therefore, you always can
determine the number of items in an object collection using the following expression:
Storing an object refer-
ence as a variable also can
speed up your programs
because it frees browsers
from having to locate the
object again within the
object hierarchy.
collection .length
Finally, as with arrays, you can use a for loop to examine all of the items within a col-
lection. The general form is
for (var i = 0; i < collection .length; i++) {
where collection is again a reference to an object collection and commands is com-
mands that can be applied to each object within the collection.
Object Collections Based on Tag Name and Class
You also can create object collections based on HTML tag names using the method
object .getElementsByTagName( tag )
where object is an object in the document and tag is the name of an HTML tag nested
within that object. For instance, the expression
creates an object collection of all h1 elements within the current document, while the
returns only the first h1 element from that collection of h1 objects.
Object collections also can be based on the value of elements' class attributes using
the method
The getElementsBy-
TagName() method can
be used to reference the
collection of all elements
in a document by using
the * wildcard character in
place of the tag name.
object .getElementsByClassName( class )
where class is the value of the class attribute from the HTML document. Thus, the
returns the collection of all elements that belong to the newGroup class. Note that the
getElementsByClassName() method is supported only in the HTML5 DOM and not in
earlier DOMs.
Search WWH ::

Custom Search