Team LiB
Previous Section Next Section

Traditional HTML Element Access with Document

The first version of JavaScript defined three collections of HTML elements for the Document object: anchors[], forms[], and links[]. Later, in browsers like Netscape 3 and Internet Explorer 4 collections like applets[], embeds[], images[], and plugins[] were made available. Many of these features continue to be supported under the DOM Level 1 and even the ones that are not in the specification will probably continue to be supported by browsers given their widespread use. Table 13-2 presents an overview of these collections.

Table 13-2: Traditional Document Collections

Collection Name

Description

Browser Compatibility

DOM Support

anchors[]

A collection of all anchors as defined by <a name="anchorname"></a>.

Netscape 2+ and Internet Explorer 3+

DOM Level 1

applets[]

All the Java applets in a page as defined by the <applet> tag.

Netscape 3+ and Internet Explorer 4+

DOM Level 1

embeds[]

All the <embed> tags in a page.

Netscape 3+ and Internet Explorer 4+

No DOM Support

forms[]

All forms in a page as set by the <form> tag.

Netscape 2+ and Internet Explorer 3+

DOM Level 1

images[]

A collection of all images in the page indicated by the HTML <img> tag.

Netscape 3+ and Internet Explorer 4+

DOM Level 1

links[]

The links in the page defined by tags of the form <a href="linkdest"></a>.

Netscape 2+ and Internet Explorer 3+

DOM Level 1

plugins[]

All the <embed> tags in a page. This collection is synonymous with embeds[], the preferred collection.

Netscape 3+ and Internet Explorer 4+

No DOM support

Besides the common collections presented in Table 13-2, traditionally the Document object also has supported the title property, which holds the title of the document as specified by the <<title>> tag within the head element of an (X)HTML document. Under traditional JavaScript, this property is a read-only string. However, under modern browsers you can set its value as well.

document.anchors[] and document.links[]

The first (X)HTML tag-related objects we examine in detail are links and anchors that have been accessible since the first versions of JavaScript. In (X)HTML, an anchor is a link that is named—in other words, it serves as a destination for other links. Anchors are defined with <<a name="anchorname">>…<</a>>. A link is also defined with the <<a>> tag but contains an href attribute setting a link destination, like so: <<a href="http://www.yahoo.com">>click me!<</a>>. Of course, it should be evident that a link can be an anchor as well, since <<a name="yahoolink"href="http://www.yahoo.com">> is perfectly valid.

The anchors[] collection doesn’t seem too useful in JavaScript because traditionally you could only access its length property using document.anchors.length. Other than that you really can’t appear to modify anything. Since under the DOM an <<a>> tag is referenced by an HTMLAnchorElement, you are certainly free to change an arbitary attribute of the tag.

The links[] collection contains all the objects corresponding to each <<a href="">> found in the document. As it is an array we can, of course, access its length with document.links.length. However, we can manipulate the URLs within the href attributes of each link. Link objects under most browsers will have the same properties as the Location object, including hash, host, hostname, href, pathname, port, protocol, and search. These properties correspond to the individual portions of a URL except href, which contains the whole URL.

Click To expand

You also can read the target property of a link to see the name of which window or frame the link will load into.

The most useful aspect of the link property is that you can set the href property after the document loads, as shown in this small JavaScript snippet.

<<a href="http://www.yahoo.com">>Test Link<</a>>
<<form action="#" method="get">>
<<input type="button" value="change link" onclick="document.links[0].href='http://www.google.com';" />>
<</form>>

JavaScript programmers should be able to dream up many useful applications for this settable property, such as making links act differently depending on user actions, the time of day, return visit, and so on.

Note 

Make sure to note that the <<area>> tags that make up the links in a client-side image map are also included in a links[] collection.

document.forms[]

Click To expand
Figure 13-2: Form field access example

The forms[] collection contains objects referencing all the <<form>> tags in a document. These can be referenced either numerically or by name. So document.forms[0] would reference the first form tag in the document, while document.forms["myform"] or document.myform would reference the form named “myform” represented by <<form name="myform">> no matter where it occurs in a document. The main properties of an individual Form (or under the DOM HTMLFormElement) object are related to the attributes of the <<form>> tag and include

  • action The URL to submit the form to as specified by the action attribute. If unspecified, the form will submit to the current document location.

  • encoding The value of the enctype attribute, generally application/x-www-form-urlencoded unless using a file upload when it should be multipart/form-data. Occasionally, value may be text/plain when using a mailto: URL submission.

  • encType The DOM property to be used in place of the traditional encoding property to access the enctype attribute’s value.

  • method The method attribute value, either get or post. The get method is the default when unspecified.

  • name The name of the form if defined.

  • target The window or frame name to display the form result within.

The Form object also specifies a length property that corresponds to the number of fields within the form defined by <<input>>, <<select>>, <<textarea>>, and possibly <<button>> in browsers that support this HTML element. Object references to these elements are stored in the elements[] collection of the Form object to be discussed next. Last, the Form object supports two methods, submit() and reset(), which correspond to the submission and resetting of the form.

Form Elements Collection

The elements[] collection for each Form object is an array containing the various fields in a form including checkboxes, radio buttons, select menus, text areas, text fields, password fields, Reset buttons, Submit buttons, generic buttons, and even hidden fields. Later JavaScript implementations also support file upload fields. Access to form elements can be performed numerically (document.myform.elements[0]) or by name (document.myform.textfield1). The number of elements in the form is accessible either with document.formname.length or document.formname.elements.length. The properties of each form field object vary based upon the HTML syntax. Let’s look at the standard text field to get the idea.

A text field in (X)HTML is defined by <<input type="text" name="fieldname" size="field size in chars" maxlength="maxlength of entry in chars" value="default text value" />>, so accordingly you would expect the properties for a text field object to be type, name, size, maxlength, and value. In the case of the DOM standard, we see that the maxlength attribute should be referenced as maxLength. Also defined is the property defaultValue, which holds the original value, specified by the value attribute since the value property of this object will change as the user changes the field. A simple example showing the manipulation of a text field is shown here.

<<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">>
<<html xmlns="http://www.w3.org/1999/xhtml">>
<<head>>
<<title>>Text Field Fun<</title>>
<<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />>
<<script type="text/javascript">>
<<!--
function showProps(textfield)
{
 var prop, str="Field Properties\n\n";
 str += "name: "+textfield.name + "\n";
 str += "type: "+textfield.type + "\n";
 str += "size: "+textfield.size + "\n";
 str += "maxLength: "+textfield.maxLength + "\n";
 str += "value: "+textfield.value + "\n";
 str += "defaultValue: "+textfield.defaultValue + "\n";
 alert(str);
}
//-->>
<</script>>
<</head>>
<<body>>
<<form action="#" method="get" id="myform" name="myform">>
<<input type="text" id="field1" name="field1" size="20" maxlength="30"
 value="initial value" />><<br />>
<<input type="button" value="Read field"
 onclick="alert(document.myform.field1.value);" />>
<<input type="button" value="Write field"
 onclick="document.myform.field1.value='Changed!!!';" />>
<<input type="button" value="Show properties"
 onclick="showProps(document.myform.field1);" />>
<</form>>
<</body>>
<</html>>

An in-depth discussion of the nuances of accessing the Form object and all of its possible contained elements is presented in Chapter 14 where we talk about form validation and other JavaScript improvements to form fill-out.

document.images[]

Netscape 3 and later Internet Explorer added the images[] collection to the Document object, which continues to be available under the DOM. Obviously, this collection contains objects related to the images defined by the (X)HTML <<img>> tag. As with other collections, the length property is available and the various images can be accessed through the collection numerically (document.images[0]) or by name (document.images['myimage']).

Once accessed, the traditional JavaScript Image object supports JavaScript properties related to its (X)HTML attributes including border, height, hspace, lowsrc, name, src, vspace, and width. The object also supports the property complete, which contains a Boolean value indicating if the image has completely loaded or not. The DOM HTMLImageElement extends this support to all other (X)HTML attributes with equivalent property names with the exception of lowsrc, ismap, longdesc, and usemap, which become lowSrc, isMap, longDesc, and useMap, respectively.

Note 

The DOM specification is related to the HTML 4 specification and not XHTML. You may even find some minor extensions beyond HTML 4 such as lowSrc. Proceed with caution if you care greatly about validatable markup.

A simple example showing the access of an image is given here and its rendering can be found in Figure 13-3.

Click To expand
Figure 13-3: Example Image properties
<<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">>
<<html xmlns="http://www.w3.org/1999/xhtml">>
<<head>>
<<title>>Image Fun<</title>>
<<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />>
<<script type="text/javascript">>
<<!--
function showProps(theImage)
{
 var prop, str="Image Properties\n\n";

 str += "alt: "+theImage.alt + "\n";
 str += "border: "+theImage.border + "\n";
 str += "complete: "+theImage.complete + "\n";
 str += "height: "+theImage.height + "\n";
 str += "hspace: "+theImage.hspace + "\n";
 // use traditional lowsrc rather than lowSrc since no IE6 support 
 str += "lowsrc: "+theImage.lowsrc + "\n";
 str += "name: "+theImage.name + "\n";
 str += "src: "+theImage.src + "\n";
 str += "vspace: "+theImage.vspace + "\n";
 str += "width: "+theImage.width + "\n";
 alert(str);
}
//-->>
<</script>>
<</head>>
<<body>>
<<img src="image1.gif" alt="The Image" lowsrc="lowres.gif" id="testimage"
 name="testimage" width="100" height="100" border="1" hspace="10" vspace="15" />>
<<br />><<br />>
<<form action="#" method="get">>
<<input type="button" value="Show properties"
 onclick="showProps(document.images['testimage']);" />>
<<input type="button" value="Swap Image"
 onclick="document.testimage.src='image2.gif';" />>
<<input type="button" value="Restore Image"
 onclick="document.testimage.src='image1.gif';" />>
<</form>>
<</body>>
<</html>>

We’ll explore all these properties again in more detail in Chapter 15 and we’ll see how to create a common JavaScript effect called the rollover button using the Image object.

Object-Related Collections: applets[], embeds[], and plugins[]

Netscape 3 and later Internet Explorer 4 supported JavaScript access to included object technologies like Java applets and Netscape plug-ins can be accessed with the applets[] and embeds[] collection, respectively. The plugins[] collection is also commonly supported and is just a synonym for the embeds[] collection. The DOM continues support only to the applets[] collection despite the fact that ActiveX controls and plug-ins far outnumber Java applets in public Web sites, so developers are encouraged to consider the lack of standard support to be an oversight.

Like the previous collections presented, these collections contain object references related to the use of the <<applet>> or <<embed>> tag, thus the length property of the collection can be accessed and the individual items in the collection can be referenced numerically (document.embeds[0]) or by name (document.myJavaApplet).

The particular properties and methods supported by each included object are not necessarily as consistent as the elements discussed so far, as it depends greatly on the included object. In the case of Java applets, the various public properties and methods of the included applet can be referenced via JavaScript, while in the case of plug-ins, the properties and methods vary from plug-in to plug-in. This would make sense since one would expect the features of an included Flash movie to be different than that of, as an example, an embedded sound file. Because of these variations, readers should look to Chapter 18 for a more complete explanation.

DHTML-Related Document Collections

Given the previous discussion, you would have expected the rise of a variety of collections for paragraphs, lists, and so on. While this might make sense, things actually degraded in a much worse fashion into the chaos of DHTML under the 4.x generation of browsers complete with proprietary collections like layers[] and all[], as discussed in Chapter 9. We’ll avoid talking about anything but document.all[], which is still used by many developers for better or worse.

Document.all[]

Under Internet Explorer, the all[] collection represents all (X)HTML elements and comments within a document. Like all (X)HTML element collections, it can be used numerically (document.all[10]) or by name (document.all['myP1']) when an (X)HTML element has an id attribute set. Named objects in Internet Explorer can all be accessed using the item method for all like so: document.all.item('myP1'). However, many JavaScript programmers will simply access the object directly by its id value like myP1. You can also use the tags() method for document.all[] to return a list of all tags of a particular type:

var allBolds = document.all.tags("B");

You can then access the returned collection as any other.

Once an element is found, the question then begs, what are its properties? Of course, this depends on the type of element being looked at. For example, if myP1 held a reference to a paragraph element you could set its alignment under Internet Explorer 4 and greater with myP1.align.

myP1.align="center";

Other HTML element objects would have properties related to their HTML attributes.

While document.all[] presents an easy way to access HTML elements, many other DHTML-related collections are not so innocuous. In reality very few of the DHTML-related collections should be used. For backward compatibility, however, you may want to become aware of DHTML collections like document.layers[] and document.all[]. Chapter 15 illustrates just such a use of both DOM and DHTML approaches in an example to move, show, and hide objects. Yet the future of JavaScript is not to continue to use all the hacks and workaround commonly employed but to migrate to the DOM standard.


Team LiB
Previous Section Next Section