PPK on JavaScript: The DOM - Part 2 | WebReference

PPK on JavaScript: The DOM - Part 2


PPK on JavaScript: The DOM - Part 2

By Peter-Paul Koch

E: Creating and cloning elements

The W3C DOM allows you to create your own elements and text nodes, and add them to the document tree. In theory, you could remove all elements from the tree, create new ones, and repopulate the tree, thus changing the page completely. In practice, this feature is used in a somewhat more restrained way.

The DOM also allows you to clone existing elements, so that you can easily duplicate a certain feature and spread copies through your document.

createElement() and createTextNode()

The createElement() method and the createTextNode() do just what their names say they will:

x refers to the newly created <p> element, while y refers to the newly created text node. These nodes aren't inserted in the document yet. You would now use appendChild() or insertBefore() to add them to the document tree. For instance:

This appends the text node to the <p>, and the <p> to the document. Now the document has one extra <p> tag as its last child.

createElement('option') - Don't Use: Don't try to create option elements through createElement(), because Explorer doesn't support it. See Section 8J for the safe way to add options to a document.

Usually you create an element and insert it into the document immediately. But you can also create elements and keep them around for future use. I do this with the extraButton in Sandwich Picker that we already saw in the appendChild() and removeChild() examples.

Right at the start, before I even run my initialization function, I create a few elements I'll need in the rest of the script:

Why Create the Button Before Initialization? Frankly I can't remember why I created this button before the official script initialization. These are real-world example scripts, so occasionally they contain real-world oddities.

If the W3C DOM is supported, the script creates a <button> element, gives it a class name for CSS purposes, appends a text node so that the user understands what the button does, and adds an onclick event handler that calls the right function.

The extra button is now ready for use, but I want it to appear only when the user orders a sandwich by entering an amount in a form field; at that moment I use appendChild() to actually add the button to the document. Until then it's quietly waiting in the DOM hyperspace we'll discuss in Section 8K; it may not ever be used.