The new nodes you’ve created aren’t yet of any practical value, as they don’t yet appear anywhere in the DOM. A few methods of the document object are specifically
designed for placing nodes in the DOM tree, and they are described in the following sections.
appendChild()
Perhaps the simplest way of all to attach a new node to the DOM is to append it as a child node to a node that already exists somewhere in the document. Doing so is just a matter of locating the required parent node and calling the appendChild() method:
Click he re to vie w code image
var newText = document.createTextNode("Here is some text content."); var myDiv = document.getElementById("id1");
myDiv.appendChild(newText);
In the preceding code snippet, a new text node has been created and added as a child node to the currently existing <div> element having an id of id1.
Tip
Remember that appendChild() always adds a child node after the last child node already present, so the newly appended node becomes the new
lastChild of the parent node.
Of course, appendChild() works equally well with all types of nodes, not just text nodes. Suppose you needed to add another <div> element within the parent <div> element:
Click he re to vie w code image
var newDiv = document.createElement("div"); var myDiv = document.getElementById("id1"); myDiv.appendChild(newDiv);
Your originally existing <div> element now contains a further <div> element as its last child; if the parent <div> element already contained some text content in the form of a child text node, then the parent div (as represented in the newly modified DOM, not in the source code) would now have the following form:
Click he re to vie w code image
<div id="id1">
Original text contained in text node <div></div>
</div>
insertBefore()
Whereas appendChild() always adds a child element to the end of the list of children, with insertBefore() you can specify a child element and insert the new node immediately before it.
The method takes two arguments: the new node, and the child before which it should be placed. Let’s suppose that your page contains the following HTML snippet:
Click he re to vie w code image
<div id="id1">
<p id="para1">This paragraph contains some text.</p> <p id="para2">Here's some more text.</p>
</div>
To insert a new paragraph between the two that are currently in place, first create the new paragraph:
Click he re to vie w code image
var newPara = document.createElement("p");
Identify the parent node, and the child node before which you want to make the insertion:
Click he re to vie w code image
var myDiv = document.getElementById("id1"); var para2 = document.getElementById("para2");
Then pass these two as arguments to insertBefore():
Click he re to vie w code image
myDiv.insertBefore(newPara, para2);
replaceChild()
You can use replaceChild() when you want to replace a current child node of a specific parent element with another node. The method takes two arguments—a
reference to the new child element followed by a reference to the old one.
Try it Yourself: Replacing Child Elements
Take a look at the code of Listing 9.3.
LISTING 9.3 Replacing Child Elements
Click he re to vie w code image
<!DOCTYPE html> <html>
<head>
<title>Replace Page Element</title> </head>
<body>
<div id="id1">
<p id="para1">Welcome to my web page.</p> <p id="para2">Please take a look around.</p>
<input id="btn" value="Replace Element" type="button" /> </div>
</body> </html>
Suppose that you want to use the DOM to remove the first paragraph in the <div> and replace it instead with an <h2> heading as follows:
<h2>Welcome!</h2>
Click he re to vie w code image
var newH2 = document.createElement("h2");
This new element needs to contain a text node for the heading text. You can either create it and add it now, or do it later when you’ve added your new <h2>
element to the DOM. Let’s do it now:
Click he re to vie w code image
var newH2Text = document.createTextNode("Welcome!"); newH2.appendChild(newH2Text);
Now you can swap out the unwanted child node of the <div> element and replace it with the new one:
Click he re to vie w code image
var myDiv = document.getElementById("id1"); var oldP = document.getElementById("para1"); myDiv.replaceChild(newH2, oldP);
Finally, you need to add an onclick event handler to the button element, so that when the button is clicked, your element replacement function is executed. We do that with an anonymous function assigned to the window.onload method:
Click he re to vie w code image
window.onload = function() {
document.getElementById("btn").onclick = replaceHeading; }
Listing 9.4 shows the code for the page with the JavaScript added.
LISTING 9.4 The Completed Code to Replace Child Elements
Click he re to vie w code image
<!DOCTYPE html> <html>
<head>
<title>Replace Page Element</title> <script>
function replaceHeading() {
var newH2 = document.createElement("h2");
var newH2Text = document.createTextNode("Welcome!"); newH2.appendChild(newH2Text);
var myDiv = document.getElementById("id1"); var oldP = document.getElementById("para1"); myDiv.replaceChild(newH2, oldP); } window.onload = function() { document.getElementById("btn").onclick = replaceHeading; } </script>
</head> <body>
<div id="id1">
<p id="para1">Welcome to my web page.</p> <p id="para2">Please take a look around.</p>
<input id="btn" value="Replace Element" type="button" /> </div>
</body> </html>
Create a new HTML file with your editor and insert the code listed in Listing 9.4. On loading the page into your browser, you should see the two single-line
paragraphs of text with the button beneath. If all has gone according to plan, clicking the button should swap the first <p> element for your <h2> heading, as depicted in Figure 9.6.
FIGURE 9.6 The element-replacement script in action
removeChild()
There is a DOM method specifically provided for removing child nodes from the DOM tree.
Referring once more to Listing 9.3, if you wanted to remove the <p> element with id="para2" you can just use
Click he re to vie w code image
var myDiv = document.getElementById("id1"); var myPara = document.getElementById("para2"); myDiv.removeChild(myPara);
Tip
If you don’t have a handy reference to the element’s parent, just use the parentNode property:
Click he re to vie w code image
myPara.parentNode.removeChild(myPara);
The return value from the removeChild() method contains a reference to the
removed node. If you need to, you can use this to further process the child node that has just been removed:
Click he re to vie w code image
var removedItem = myDiv.removeChild(myPara);
alert('Item with id ' + removedItem.getAttribute("id") + ' has been removed.');