Java Reference
In-Depth Information
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 fi rst
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.
Manipulating the DOM
As mentioned at the very beginning of this chapter, Dynamic HTML is the manipulation of an HTML
page after it's loaded into the browser. Up to this point, you've examined the properties and methods of
the basic DOM objects and learned how to traverse the DOM through JavaScript.
Throughout the previous section, you saw some examples of manipulating the DOM; more specifi cally,
you saw that you can change the color and font family of text contained within an element. In this sec-
tion, you'll expand on that knowledge.
Accessing Elements
As you saw in the previous section, the DOM holds the tools you need to fi nd and access HTML ele-
ments; you used the getElementById() method quite frequently, and through examples you saw how
easy it was to fi nd specifi c elements in the page.
When scripting the DOM, chances are you have a pretty good idea of what elements you want to manip-
ulate. The easiest way to fi nd those elements is to use the id attribute and thus the getElementById()
method. Don't be afraid to assign id attributes to your HTML elements; it is by far the easiest and most
effi cient way to fi nd elements within the page.
Changing Appearances
Probably the most common DOM manipulation is to change the way an element looks. Such a change
can create an interactive experience for visitors to your web site and can even be used to alert them to
important information or that an action is required by them. Changing the way an element looks con-
sists almost exclusively of changing CSS properties for an HTML element. You can do this two ways
through JavaScript:
Change each CSS property with the
style property.
Change the value of the element's
class attribute.
Search WWH ::




Custom Search