14.9 Creating a New Element

NN 6, IE 5

14.9.1 Problem

You want to generate a brand new element and insert it into the body of the current page.

14.9.2 Solution

For IE 5 or later and Netscape 6 or later, use the W3C DOM element-creation method of the document object. The sole parameter is a string of the tag name for the element:

var elem = document.createElement("p");

You can now populate the element with properties and other content, and then insert it into the document.

14.9.3 Discussion

The tag name you supply as a parameter to the createElement( ) method can be upper- or lowercase, but in keeping with current trends in XHTML practice, lowercase is the preferred style. Your case choice does not influence the value returned by the element's tagName property, which uniformly returns values in all uppercase.

Invoking the createElement( ) method generates the element in the browser's memory, but the element is not yet part of the document node tree. To accomplish this task, use one of the node tree modification methods on the element that you want to be the parent node of the newly installed element:

appendChild( newChild)

Adds the newChild node as the last child of the element invoking the method. Returns a reference to the newly appended child node.

insertBefore( newChild, refNode)

Inserts the newChild in front of the existing child node referenced by refNode. Returns a reference to the newly inserted child node.

replaceChild( newChild, oldChild)

Inserts the newChild in place of the oldChild. Returns a reference to the removed child node.

Here is a typical sequence that creates a new self-contained element, sets various attributes, and puts it at the end of the page's body:

var elem = document.createElement("img");
elem.setAttribute("src", "images/logo.jpg");
elem.setAttribute("height", "40");
elem.setAttribute("width", "120");
elem.setAttribute("alt", "GiantCo Logo");

The previous sequence uses the setAttribute( ) method to assign values to what are normally attribute values of the tag. You can also assign values to the analogous properties of the element object, but the W3C DOM recommendation prefers the setAttribute( ) method for this purpose. Your choice is strictly based on programming style, in that browsers recognize both syntaxes equally (and the property assignment approach is less verbose).

You also are not required to set the attributes of the element prior to inserting the element into the document tree. Again, this is a programming style decision, but it is quite typical to load an object with all its values before presenting it to the environment. In rare instances, however, an element must become part of the document tree for a scripted property to be accessible because it needs a layout context for the property assignment to take effect (see Recipe 14.12).

Internet Explorer (dating back to Version 4) has a supplementary vocabulary (and mind-set) for creating elements and inserting them into a document. The system is not node-oriented in the way the W3C DOM is. Instead, it works with HTML as strings. Rather than generating a new element object, simply assemble the HTML for the new element as a string, and then insert the string in the desired place within the document structure. The IE-only equivalent of the img element creation sequence shown earlier is:

var elem = "<img src='images/logo.jpg' height='40' width='120' alt='GiantCo Logo'>";
document.body.insertAdjacentHTML("BeforeEnd", elem);

The first parameter of the insertAdjacentHTML( ) method instructs the browser to insert the new string just inside the </body> tag of the document, while the method forces the browser to treat the string as HTML so that the tags are treated as markup, rather than as completely literal strings (displaying the angle brackets, attributes, and so on).

It's quite clear that the HTML-string approach is simpler in many respects, especially if you've been using it to script IE that way for years. But the W3C DOM through Level 2 does not (and likely will not) provide a convenient way to deal with tagged content in string form. See Recipe 14.10 for one IE convenience that has made its way to the Mozilla browser for element text.

14.9.4 See Also

Recipe 14.10 for generating text content of an element; Recipe 14.11 for creating a combination of element and text nodes for insertion into a document; Recipe 14.12 for inserting an iframe into a document.