A newly-created element starts off empty and untethered. Before it can be displayed, it needs some content, and it must be attached to some part of the document tree.
Here are the basic steps. Create and populate the element:
Then add the element to the document, using one of the following methods:
Alternatively, major browsers also implement an innerHTML property. This Microsoft extension is not part of the DOM specification, but it is a simple way to set or read the entire contents of an element. You'll find both approaches illustrated below.
This page will show how to create two new elements:
What the browser creates from this markup
<p id="viola" class="example">My new paragraph.</p>
you can create on-the-fly with this code:
var newP = document.createElement("p"); // create a new paragraph newP.setAttribute("id", "viola"); // assign it an ID (optional — for locating later) newP.setAttribute("class", "example"); // assign it to a class (optional — for style) var p_text = document.createTextNode("My new paragraph."); // create some content newP.appendChild(p_text); // append the content to "newP"
Remember: all elements are given a basic set of tools, or "methods" — not unlike carpenters, each outfitted with a personal tool belt. As you can see above, once DOCUMENT has created the new P element, you use P's own methods to assign it features and append its text.
Now, "newP" is ready to be attached to some part of the document.
Put "newP" at the bottom of the page, after all BODY's other children:
document.body.appendChild(newP);
The code above locates BODY inside DOCUMENT and run's BODY's "appendChild" method.
Put "newP" at the top of the page, in front of all BODY's children:
document.body.insertBefore(newP, document.body.firstChild); // before BODY's firstChild
Note: unlike "appendChild", "insertBefore" needs to know before what:
The code above might be more readable if you created a variable to stand-in for "document.body". Like this:
var B = document.body; B.insertBefore(newP, B.firstChild);
You can use the same approach to attach "newP" to any other element you can find. Assume your page contains a DIV with the ID of "demo":
var D = document.getElementById("demo"); // find "demo" // any of these commands will add "newP" to "demo's" descendents D.appendChild(newP); // append to "demo" D.insertBefore(newP, D.firstChild); // insert as "demo's" 1st child D.replaceChild(newP, D.firstChild); // replace "demo's" 1st child D.insertBefore(newP, D.childNode[1]); // insert as 2nd child D.insertBefore(newP, D.lastChild); // insert as next-to-last child
By using "demo's" relationship properties, you can attach "newP" near to "demo":
D.parentNode.insertBefore(newP, D); // insert "newP" before "demo" D.parentNode.insertBefore(newP, D.previousSibling); // before "demo's" previous sibling D.parentNode.insertBefore(newP, D.nextSibling); // insert after "demo" D.parentNode.insertBefore(newP, D.nextSibling.nextSibling); //after "demo's" next sibling
The above may look dense, but it merely locates "demo's" parent, then uses that parent's methods. (It's sort of like buildng a little garden shed, trucking it over to Earl's place, and saying, "Find Earl's dad and ask him to put this shed in front of Earl's.)
Again, if you'll perform several operations using the parent node of an element, you may want to define it as a separate variable first:
var P = D.parentNode; // make P refer to D's parent
P.insertBefore(newP, D);
P.insertBefore(newP, D.nextSibling);
The steps above use the tools defined by the DOM standard, and they give you a lot of flexibility. The new paragraph can be inserted among other elements, or it can replace an element of your choice.
However, if you wanted to replace the entire contents of the "demo" DIV, you could do it using the non-standard "innerHTML" property:
var D = document.getElementById("demo"); // locate "demo" // replace all its contents with the new paragraph D.innerHTML = "<p id="viola" class="example">My new paragraph.</p>";
While innerHTML is compact and easy to read, the DOM methods give you more selective control. And since they're part of an open standard, they're more likely to be implemented similarly across browsers.
On the other hand, innerhtml is implemented in Mozilla, Opera, and Safari, as well as Internet Explorer. And Internet Explorer 6 doesn't correctly follow the DOM in all cases, so you sometimes need to fall back on innerhtml, regardless of equivalent methods in the DOM.
An element can be attached only to one ancestor at a time. If you attach an element to a 2nd location, it will be removed from its original position.
Try it out. Insert a new paragraph above this one. Then insert it again after this paragraph. Finally, remove the paragraph from the document.
An element cannot remove itself, but its parent can:
// to remove an element
var newP = document.getElementById("viola");
newP.parentNode.removeChild(newP);
Note: the optional ID "viola", added when we created the paragraph, helps us find it here.
In the example above, the paragraph contains a single text node. The following example illustrates creating a paragraph with more complex content. It requires no new methods, but does require that the content be assembled in the right order.
Consider this markup:
<p id="plink">Click <a href="more.html">here</a> for more info.</p>
A browser displays this as a single sentence, but it's built from 3 parts:
The next lines would create the paragraph in real time. They could be implemented in a different order, but for clarity, they first create a complete link, then create the paragraph:
// create the new link var newA = document.createElement("a"); // create a new anchor newA.setAttribute("href","more.html"); // create its hypertext reference var a_text = document.createTextNode("here"); // create A's text node newA.appendChild(a_text); // append A's text node // create the new paragraph var newP = document.createElement("p"); // create a new paragraph newP.setAttribute("id", "plink"); // assign it an ID // create the paragraph's text nodes var p_text0 = document.createTextNode("Click "); // create P's 1st text node var p_text1 = document.createTextNode(" for more info."); // create P's 2nd text node // assemble the paragraph newP.appendChild(p_text0); newP.appendChild(newA); // the entire link is inserted here newP.appendChild(p_text1);
"newP" is now ready to be attached to the document using any of the methods shown in the previous example.
What happens, though, if you need to insert a phrase into the middle of a sentence, or italicize a word, or change a normal word into an active link?
The next page shows how to divide simple text nodes into more complex structures, and how to recombine them when appropriate.