188Part IIIDocument Objects ReferenceNow the (Web site template) script is ready
188Part IIIDocument Objects ReferenceNow the script is ready to invoke the replaceChild()method on the emelement, swappingthe old text node with the new: document.getElementById( emphasis1 ).replaceChild(newText, oldChild); If you want to capture the old node before it disappears entirely, be aware that thereplaceChild()method returns a reference to the replaced node (which is only in mem- ory at this point, and not part of the document node hierarchy). You can assign the methodstatement to a variable and use that old node somewhere else, if needed. This may seem like a long way to go; it is, especially if the HTML you are generating is com- plex. Fortunately, you can take a simpler approach for replacing text nodes. All it requires is areference to the text node being replaced. You can assign that node s nodeValueproperty itsnew string value: document.getElementById( emphasis1 ).childNodes[0].nodeValue = first ; When an element s content is entirely text (for example, a table cell that already has a text nodein it), this is the most streamlined way to swap text on the fly using W3C DOM syntax. Thisdoesn t work for the creation of the second paragraph text earlier in this chapter because thetext node did not exist yet. The createTextNode()method had to explicitly create it. Also remember that a text node does not have any inherent style associated with it. The styleof the containing HTML element governs the style of the text. If you want to change not onlythe text node s text but also how it looks, you have to modify the styleproperty of the textnode s parent element. Browsers that perform these kinds of content swaps and stylechanges automatically reflow the page to accommodate changes in the size of the content. To summarize, Listing 14-2 is a live version of the modifications made to the original docu- ment shown in Listing 14-1. The new version includes a button and script that makes thechanges described throughout this discussion of nodes. Reload the page to start over. Listing 14-2: Adding/Replacing DOM Content
This is the one andonly paragraph on the page.