HTML and CSS Reference
In-Depth Information
Figure 1-21 shows that when this code is run in the browser, the
innerDiv
element has been
removed.
FIGURE 1-21
Using the
removeNode
method to remove the
<div>
node
Now, suppose that you want to change the content of the page more dramatically—per-
haps even by rewriting all the HTML content. This is completely possible with the techniques
you have seen so far, but you haven't tried some methods yet:
replaceNode
and
replaceChild
.
These two methods operate in the same way as
removeNode
and
removeChild
in terms of the
parameters they take and which elements they affect. The difference, however, is that you can
replace the target element with a completely new element. The following code converts all
your inner paragraphs to anchor elements and adds line breaks, because you don't get those
automatically as you do from the
<p>
element:
var innerDiv = document.getElementById("innerDiv");
var newDiv = document.createElement("div");
for (var i = 0; i < innerDiv.childNodes.length; i++) {
var anchor = newDiv.appendChild(document.createElement("a"));
anchor.setAttribute("href", "http://www.bing.ca");
anchor.text = innerDiv.childNodes[i].textContent;
newDiv.appendChild(document.createElement("br"));
}
innerDiv.replaceNode(newDiv);
This code produces the browser output as shown in Figure 1-22.
Search WWH ::
Custom Search