Creating New Elements
Elements can be added to the document using one of two techniques:
creating a new element in memory and associating it with the document, or directly modifying
the underlying HTML contents. The direct modification of the
underlying HTML contents is discussed in Chapter 13, "Dynamic Contents."
This section demonstrates the first technique, creating elements in memory.
Some elements can be created by using the
createElement method on the document or by using the
new operator on the window. Both methods perform
the same action and return a new element object. The
createElement method is a language-independent mechanism for constructing elements; the
new operator is provided for compatibility with Netscape Navigator. The newly created element
object is not maintained in memory and is not associated with the document until it
is explicitly added to the document. The following code demonstrates using both
techniques to create an IMG element:
var img = new Image();
var img = document.createElement("IMG");
Internet Explorer 4.0 allows the creation of only three elements in this fashion:
IMG, Option, and Area.
You can dynamically add new Option and Area elements to list boxes
and image maps, respectively. The construction of images is currently limited to
allowing images to preload into the cache. The IMG element itself cannot be added to
the document. Instead, because the construction forces an image to
download into the cache, simply assigning the URL of the image to the
src
attribute of an existing image causes the new image to display, as shown here:
var img = new Image();
img.src = "cool.gif"; // Download the image in the background.
document.all.myImage.src = "cool.gif"; // Use downloaded image.
New Option and Area elements can be added to the document. The Select
element exposes an options collection of the Option elements it contains, and the Map
element exposes an areas collection of the Area elements it contains. These
collections allow additional Option or Area elements to be dynamically added or removed.
The technique for adding and removing these elements plus examples of
how to take advantage of preloading images are discussed in the next two
chapters. All other contents in the document's Body element can be modified
by directly changing the HTML, as discussed in Chapter 13, "Dynamic Contents." [Содержание]
|