Section 10.7. Modifying the Tree


10.7. Modifying the Tree

The document is the owner/parent of all page elements. Because of this, most factory methods to create instances of new elements are methods on the Core document object. The Node, though, maintains the navigation within the Core API. This supports the hierarchical structure of the document tree, in which each node has a relationship to other nodes, and navigation follows this natural structure: parent/child, sibling/sibling. Finally, the Element provides a way to access elements within context in order to apply changes to nested elements. All three are essential objects when it comes to modifying the document tree.

The document factory methods, and the type of Core objects they create, are listed in Table 10-1. This also provides a brief introduction to several of the Core objects.

Table 10-1. Factory methods of the Document object
MethodObject created Description
createElement(tagname)

Element

Creates an element that is cast to the specific tag
createDocumentFragment

DocumentFragment

The DocumentFragment is a lightweight document, used when extracting a section of the document tree
createTextNode(data)

Text

Holds any text in the page
createComment(data)

Comment

XML comment
createCDATASection(data)

CDATASection

CDATA section
createProcessingInstructions(target,data)

ProcessingInstruction

XML processing instruction
createAttribute(name)

Attr

Element attribute
createEntityReference(name)

EntityReference

Placeholder for an element to be placed later
createElementNS (namespaceURI,qualifiedName)

Element

Namespace for Element
createAttributeNS (namespaceURI,qualifiedName)

Attr

Namespace for Element attribute


It's simple to create a new node. Call the appropriate factory method on the document, and the node is returned:

var txtNode = document.createTextNode("This is a new text node");

The new operator is not used, as interfaces aren't classes; they have no constructors.

Once you have a new node, you can manipulate it as you would manipulate an existing page element of the same type. For instance, to add HTML to the object, you can use the innerHTML property:

var newDiv = document.createElement("div"); newDiv.innerHTML = "<p>New paragraph</p>";

Use the Node modification methods to add the new node once it's ready:


insertBefore(newChild,refChild)

Inserts new node before existing


replaceChild(newChild,oldChild)

Replaces existing node


removeChild(oldChild)

Removes existing child


appendChild(newChild)

Appends child node to document

Remember, though, that these methods have to be used within context to be effective. In other words, they have to operate on the element that contains the nodes that are being replaced or removed (or where the new node is being placed).

If the web page has a DIV element with a nested H1 header, and it's the header being replaced, you'll need to access the DIV element in order to modify its structure:

var div = document.getElementById("div1"); var hdr = document.getElementById("hdr1"); div.removeChild(hdr); ... <div > <h1 >Header</h1> </div>

Demonstrating this more comprehensively, Example 10-10 is a variation of the static page that's used in previous examples in the chapter. It contains paragraphs, DIV blocks, an image, and a header. The script consists of a function, changeDoc, that's accessed when the page is clicked.

Example 10-10. Modifying a document

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Modifying Document</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript"> //<![CDATA[ document.onclick=changeDoc; function changeDoc(  ) {    // first, remove header    var hdr = document.getElementById("hdr1");    var div = document.getElementById("div1");    div.removeChild(hdr);    // replace the image with text    var img = document.getElementById("img1");    var p = document.getElementById("p2");    var txt = document.createTextNode("New text node");    p.replaceChild(txt,img);    // add new element    var div2= document.createElement("div");    div2.innerHTML="<h1>The End</h1>";    document.body.appendChild(div2); } //]]> </script> </head> <body> <div > <h1 >Header</h1> <!-- paragraph one --> <p >To better understand the document tree, consider a web page that has a head and body section, has a page title, and contains a DIV element that itself contains an H1 header and two paragraphs. One of the paragraphs contains <i>italicized text</i>; the other has an image--not an uncommon web page.</p> </div> <!-- paragraph two --> <p >Second paragraph with image. <img  src="/books/4/327/1/html/2/dotty.gif" alt="dotty" /></p> </body> </html>    

The first modification to the document is to remove the header from the DIV block. To do this, the DIV is accessed using getElementById. The header element is also accessed using this method, and once accessed, it's passed to the removeChild method on the DIV block. This removes the element from the pagecompletely.

The next modification replaces the image contained in the last paragraph with text created using a text node. First, the image and paragraph are both loaded into JavaScript variables using geTDocumentById (any method will do, as long as it's precise and returns the elements as nodes). A new text node is then created. It, and the image node, are passed to the replaceChild method on the paragraph node.

The last modification inserts a new DIV element, using innerHTML (discussed in Chapter 9) to create a new paragraph. This is appended to the body element, which results in a new header printed out at the end of the document that reads, "The End."

And it is the endof this chapter, that is. There's plenty more still to come.




Learning JavaScript
Learning JavaScript, 2nd Edition
ISBN: 0596521871
EAN: 2147483647
Year: 2006
Pages: 151

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net