Web hosting uk - 187Chapter 14Document Object Model EssentialsThe new element has

187Chapter 14Document Object Model EssentialsThe new element has no ID, attributes, or any content. To assign some attributes to that ele- ment, you can use the setAttribute()method (a method of every element object) or assigna value to the object s corresponding property. For example, to assign an identifier to the newelement, use eithernewElem.setAttribute( id , newP ); ornewElem.id = newP ; Both ways are perfectly legal. Even though the element has an ID at this point, it is not yetpart of the document so you cannot retrieve it via the document.getElementById() method. To add some content to the paragraph, you next generate a text node as a separate object: var newText = document.createTextNode( This is the second paragraph. ); Again, this node is just sitting around in memory waiting for you to apply it as a child of someother node. To make this text the content of the new paragraph, you can append the node asa child of the paragraph element that is still in memory: newElem.appendChild(newText); If you were able to inspect the HTML that represents the new paragraph element, it wouldlook like the following:

This is the second paragraph.

The new paragraph element is ready for insertion into a document. Using the documentshown in Listing 14-1, you can append it as a child of the bodyelement: document.body.appendChild(newElem); At last, the new element is part of the document containment hierarchy. You can now refer- ence it just like any other element in the document. Replacing node contentThe addition of the paragraph shown in the last section requires a change to a portion ofthe text in the original paragraph (the first paragraph is no longer the one and only para- graph on the page). As mentioned earlier, you can perform text changes either via thereplaceChild()method or by assigning new text to a text node s nodeValueproperty. Let s see how each approach works to change the text of the first paragraph s emelementfrom one and only to first. To use replaceChild(), a script must first generate a valid text node with the new text: var newText = document.createTextNode( first ); The next step is to use the replaceChild()method. But recall that the point of view for thismethod is the parent of the child being replaced. The child here is the text node inside the emelement, so you must invoke the replaceChild()method on the emelement. Also, thereplaceChild()method requires two parameters: the first is the new node; the second is areference to the node to be replaced. Because the script statements get pretty long with thegetElementById()method, an intermediate step grabs a reference to the text node insidethe emelement: var oldChild = document.getElementById( emphasis1 ).childNodes[0];

Leave a Reply