Java Reference
In-Depth Information
You start at the bottom of your tree first, by creating a text node with the createTextNode() method.
Then use the createElement() method to create an HTML heading.
At this point, the two variables are entirely separate from each other. You have a text node, and you
have an <h1/> element, but they're not connected. The next line enables you to attach the text node
to your HTML element. You reference the HTML element you have created with the variable name
newElem , use the appendChild() method of your node, and supply the contents of the newText variable
you created earlier as a parameter:
newElem.appendChild(newText);
Let's recap. You created a text node and stored it in the newText variable. You created an <h1/>
element and stored it in the newElem variable. Then you appended the text node as a child node to the
<h1/> element. That still leaves you with a problem: You've created an element with a value, but the
element isn't part of your document. You need to attach the entirety of what you've created so far to
the document body. Again, you can do this with the appendChild() method, but this time call it on the
document.body object (which, too, is a Node ):
document.body.appendChild(newElem);
This completes the first part of your code. Now all you have to do is repeat the process for the <p/>
element:
newText = document.createTextNode("This is some text in a paragraph");
newElem = document.createElement("p");
newElem.appendChild(newText);
document.body.appendChild(newElem);
You create a text node first; then you create an element. You attach the text to the element, and finally
you attach the element and text to the body of the document.
It's important to note that the order in which you create nodes does not matter. This example
had you create the text nodes before the element nodes; if you wanted, you could have created the
elements first and the text nodes second.
However, the order in which you append nodes is very important for performance reasons. Updating
the DOM can be an expensive process, and performance can suffer if you make many changes to the
DOM. For example, this example updated the DOM only two times by appending the completed
elements to the document's body. It would require four updates if you appended the element to the
document's body and then appended the text node to the element. As a rule of thumb, only append
completed element nodes (that is, the element, its attributes, and any text) to the document whenever
you can.
Now that you can navigate and make changes to the DOM, let's look further into manipulating
DOM nodes.
Search WWH ::




Custom Search