Приглашаем посетить
Автомобили (auto-2000.niv.ru)

Using the Collections

Using the Collections

This section focuses on using the all collection to access the elements on the page. The all collection in the document object represents every element in the HTML file. It is manipulated using a set of properties and methods that all the element collections support. These properties and methods specify how many elements are in the collection, provide access to the individual elements, and provide the ability to filter the collection based on element type.


NOTE: Because all the collections share a common set of properties and methods, all the members discussed here can be used with any element collection in the document.


Collection Size

The first and most fundamental operation on a collection is determining the number of elements in the collection. The number of elements is returned by the length property. For example, the sample document at the beginning of this chapter has six elements:

alert(document.all.length);   // 6 elements

Accessing Elements

Elements in collections are accessed using the item method. The item method takes either an ordinal position or a string identifier representing the name or id attribute of an element. When you are supplying an ordinal position, keep in mind that all collections are zero-based. Therefore, the following code enumerates the elements in the all collection:

// Display the tag name for each element.
for (var i = 0, i < document.all.length, i++)
   alert(document.all.item(i).tagName);


NOTE: In a loop like this that accesses the elements of a collection, the conditional expression must test that the index is less than the length of the collection. Because the collection is zero-based, it has no element whose index equals the collection's length.

In VBScript, item is the default method on collections; specifying the item method is optional when you are accessing elements. In JavaScript, default methods are not supported; however, all objects are associative arrays, allowing all named elements to be accessed using the array lookup notation. For collections, this means that all elements in the collection are also exposed as properties on the object, which allows the elements to be accessed by their ordinal position in the underlying array or by their string name or ID. The preceding code fragment can be rewritten as follows:

// Display the tag name for each element.
for (var i = 0, i < document.all.length, i++)
   alert(document.all[i].tagName);


NOTE: In JavaScript, referencing into an array is done using square brackets ([]). In VBScript, because the default method is used instead of an array, the reference uses parentheses:

msgbox(document.all(i).id)   ` VBScript


The id and name Attributes

Up to now, only referencing the item by ordinal position has been demonstrated. Referencing elements can also be done directly by using the id or name attribute. There are a few distinctions between id and name. The id attribute is supposed to uniquely identify an element within the document. The name attribute can be shared by multiple elements; it is exposed only by certain elements and usually has a specific meaning. For example, on an element in a form block, the name attribute is used as the submit name, and on multiple radio buttons, the name attribute is used to group the buttons.

When you are assigning names for programmatic access, the id attribute should be used. The name attribute should be reserved for its intended behavior based on the element's context. You may need to use name if you are writing code to run on Netscape Navigator, as it currently does not recognize the id attribute on any element other than elements positioned with CSS (Cascading Style Sheets) positioning. The name attribute is supported in Netscape Navigator to access the Form element, frames, and all built-in controls.


NOTE: To simplify terminology, from here on the term named ele- ment refers to an element that has either the id or name attribute set.

Referencing Named Elements

In JavaScript, you can use a name or an id to reference an element in three ways: using the collection's item method, directly as a property of the collection, or indirectly as an array lookup. The following examples illustrate the three ways to reference an element whose name or id is myElement:

document.all.item("myElement")
document.all.myElement
document.all["myElement"]

When you are referencing elements using the item method or an array index on the all collection, you can query for an element by passing a variable. This technique is useful because the id or name attribute does not have to be known in advance and hard-coded. You can write generic code with a variable that contains the id attribute, as shown here:

// Get the tag name for the element with the specified id.
var retValue = window.prompt("Enter an ID:");
if (retValue != null)
   alert(document.all[retValue].tagName);

Using the item Method to Return a Collection

An element's name does not have to be unique in a document. Radio buttons in a group typically share the same name, as in the following example:

<HTML>
   <HEAD>
      <TITLE>Radio Button Group</TITLE>
   </HEAD>
   <BODY>
      <FORM>
         Name: <INPUT TYPE=TEXT NAME="YourName"><BR>
         <INPUT TYPE=RADIO NAME="Gender" VALUE="Male">Male
         <INPUT TYPE=RADIO NAME="Gender" VALUE="Female">Female
      </FORM>
   </BODY>
</HTML>

Because name need not be unique, a name string you use to look up a collection element can match more than one element. When more than one element matches, the result of the lookup is a new subcollection containing all the elements with the given name. The following examples access named elements in the preceding code:

document.all["YourName"]        // Input box (not a collection)
document.all["Gender"]          // Collection of two elements
document.all["Gender"].length   // 2
document.all["Gender"].item(0)  // Male radio button

The subcollection follows the same rules as all other collections; in particular it exposes a length property and an item method. Its elements are in the same order as they are in the original collection.

When the item method returns a subcollection, you can pass a second parameter to select an element in the subcollection. For example, the Male radio button can be accessed this way:

document.all.item("Gender", 0)

VBScript and JavaScript each support a shortcut for accessing elements in a subcollection without using the item method. For example, the following code fragments both access the Male radio button:

` In VBScript, item is the default method.
document.all("Gender", 0)

// JavaScript uses array access.
document.all["Gender"][0]

Documents with duplicate ids are technically invalid, but nothing stops a developer from authoring them, and your scripts that access unknown documents in other frames or windows may encounter them. The following example code contains several elements with the id test:

<HTML>
   <HEAD>
      <TITLE>Duplicate IDs</TITLE>
   </HEAD>
   <BODY>
      <H1 ID="test">Header 1</H1>
      <P ID="test">This is a paragraph.
      <P ID="test">This is another paragraph.
      <INPUT ID="test" NAME="foo">This is a named Input box.
   </BODY>
</HTML>

Duplicate ids are handled just like duplicate names. If a script looks up an element by an id and more than one element matches the id, all of the

elements are returned as a collection. The following expressions access elements in the preceding code that have the id test:

document.all["test"].length            // 4
document.all.test.length               // 4 (look up directly by id)
document.all.test.tags("P").length     // 2
document.all.test.item("test").length  // 4 (redundant code)

The Input box in the preceding code is an interesting element. It is part of the collection returned by item("test") and is exposed individually as item("foo"). The Input box can also be accessed through the collection of elements with id test:

document.all.test.item("foo").tagName  // INPUT
document.all.foo.tagName               // Also INPUT

If an element's name and id attributes have the same value, it nonetheless appears only once in a collection of elements with that name or id. An element can exist only once in any collection.

Distinguishing Between a Collection and an Element

When your code accesses an element by its name or id, either a collection or an element may be returned. Therefore, your code might need to distinguish whether the returned object is an element or a collection. In JavaScript, the length property returns null for single elements and the numbers of elements for collections. The length property returns null for a single element because it does not actually exist on the object—JavaScript automatically adds the length property to the object with the default value of null.

The following code demonstrates how to check whether a collection or a single element is returned:

// Using length
if (null == document.all["Gender"].length) {
   // Single element
}
else {
   // Collection 
}


NOTE: You cannot use length in VBScript to differentiate individual elements from collections. If you do, VBScript generates an error because the property does not exist on the element object.

Referencing Unknown Element Names

If the item method is called using a name or an id attribute that does not exist in the document or that has not loaded yet, the method returns a null object:

var el = document.all.item("foo");
if (null == el) 
   alert("Please try again when the page is loaded.");
else {
   // Do something with the element named foo.
}

Directly Accessing Named Elements

In addition to being accessible through collections, some named elements are also properties of the document or the window. These elements are added to the document and the window purely for backward compatibility; the recommended way to access them is to use the all collection.

Elements of the following types are added directly to the document if they have a name or an id attribute: Form, IMG, and Applet. In addition, all elements with an id attribute except input elements in a form are added directly to the window, which allows you to access them without going through the document's all collection:

<H1 ID="myH1">Welcome to My Page</H1>
<FORM ID="form 1">
   <INPUT TYPE=TEXT ID="text1">
</FORM>
<SCRIPT LANGUAGE="JavaScript">
   // Access myH1 as a window property.
   alert(myH1.id);  // Output the id.
   // Access myH1 through the all collection.
   alert(document.all.myH1.id);
   // Input elements within a form are available through the form.
   alert(form1.text1.id);
</SCRIPT>

Built-In Collections

The document exposes a number of predefined collections, which all follow the set of rules introduced earlier in this chapter. These collections are provided for compatibility with older browsers. The following table lists the collections and the tags of the elements contained within them.


Collection Tags Description
all All tags Every element in the document, in source order.
anchors <A NAME…=> Bookmarks.
applets <APPLET>; <OBJECT> Embedded objects and Java applets.
forms <FORM> Forms.
frames <IFRAME> Inline frames.
images <IMG> Images.
links <A HREF=…>; <AREA> Links. If an Anchor element contains both a NAME and an HREF attribute, it will be exposed in both the links and the anchors collections.
scripts <SCRIPT> Scripts.

Rather than extend this list for arbitrary tags, collections expose the tags method for creating a new collection filtered by a specified tag. The tags method eliminates the need to clutter the object model with a collection for every element type and lets the developer determine which elements are interesting.

The tags Method

In addition to the item method, all document element collections expose a tags method. The tags method takes a parameter representing the tag as a string and returns a collection of all elements with that tag, as shown in the following code:

<HTML>
   <BODY>
      <H1>My Header</H1>
      <P>This is <STRONG>strong text</STRONG> and more 
         <STRONG>strong</STRONG> text.</P>
      <H1>Another Header 1</H1>
   </BODY>
</HTML>

The following expressions use the tags method to create collections of elements from the preceding code:

document.all.tags("H1")         // Collection of both H1 elements
document.all.tags("STRONG")     // Collection of both Strong elements
document.all.tags("STRONG")[0]  // First Strong element
document.all.tags("P").length   // 1

Unlike the item method, the tags method always returns a collection, even if only a single element exists on the page. For example, calling the tags method on the Body element still returns a collection, even though only a single Body element can exist:

document.all.tags("Body")     // A collection with one Body element 
document.all.tags("Body")[0]  // The first element in the collection

The tags method always returns a collection because it was designed with a single purpose, to filter a collection to a smaller collection. The item method returns the single element that matches the identifier—and where there are duplicate matches, a collection rather than an error is returned.

Empty Collections

If the tags method is called to query for a tag that does not exist in the document, an empty collection with zero elements is returned:

if (0 == document.all.tags("H1").length)
   alert("There are no H1 elements in this document.");

In order to ensure that even unknown elements can be queried and filtered for, the tags method does not return an error when passed to an invalid tag.

Custom Collections

Most of the document's built-in collections are the same as collections you can create using the tags method with the all collection. For example, the forms collection is the same as the collection created by calling the tags method and supplying form as the parameter. The following code creates a collection equivalent to the forms collection:

document.myforms = document.all.tags("form");

You can create custom collections and add them to the document object using a similar technique, as shown here:

// Create a tables collection on the document.
document.tables = document.all.tags("TABLE"); 

This technique relies on a language feature supported by JavaScript, so this code cannot run in VBScript and might not be capable of running under other languages. In VBScript, you must create a variable to hold the collection.

The preceding code demonstrates that multiple collections often refer to the same set of elements. Therefore, referencing an element in any of the collections is the same as referencing that element in the all collection. For example, the following code fragment returns true because the same object is being referenced through two different collections:

// Both expressions point to the same object.
document.forms[0] == document.all.tags("FORM")[0];

The all Collection in a Frameset Document

A document that contains a frameset also supports the document object and exposes the same all collection. The Frameset element replaces the Body element in the all collection because a document can contain traditional body contents or a frameset, but not both. All the Frameset and Frame elements in the document are exposed in source code order, as shown here, which is useful for determining the visual layout of the frames on the screen:

<HTML>
   <HEAD>
      <TITLE>Frameset Demo</TITLE>
   </HEAD>
   <FRAMESET ROWS="60, *"> 
      <FRAME SRC="a.htm">
      <FRAME SRC="b.htm">
   </FRAMESET>
</HTML>

The all collection for this document exposes the elements in the following order: HTML, Head, Title, Frameset, Frame, Frame.

In addition, all attributes of the Frameset and Frame elements are exposed through the all collection. Most of the attributes can be assigned a new value, but in some cases that value is not reevaluated—for example, the border of the frameset cannot be modified once the frameset is rendered. However, a frameset will update correctly if you change its row or col attribute, or if you change the src or name attribute of one of the frames.

Collections in frameset documents differ from those in other documents with respect to their inclusion of unrecognized elements. Only unrecognized elements that appear before the first <FRAMESET> tag are exposed in the object model. Once a <FRAMESET> tag is encountered, all elements other than Frameset and Frame are ignored and are not surfaced in the object model. Even NoFrames elements are ignored. If a NoFrames element appears before the Frameset element, it is exposed in the all collection, but the contents of the element are not available. This limitation may be removed by a future version of Internet Explorer.

[Содержание]