Java Reference
In-Depth Information
This HTML page contains one <p/> element with an id value of paragraph1. You use this value in
the JavaScript code to fi nd the element node and store its reference in the pElement variable with the
getElementById() method.
var pElement = document.getElementById(“paragraph1”);
Now that you have a reference to the element, you use the setAttribute() method to set the align
attribute to center .
pElement.setAttribute(“align”, “center”);
The result of this code moves the text to the center of the browser's window.
You then use the getAttribute() method to get the align attribute's value and display it in an alert box:
alert(pElement.getAttribute(“align”));
This code displays the value “center” in the alert box.
Finally, you remove the align attribute with the removeAttribute() method, effectively making the
text left-aligned.
Strictly speaking, the align attribute is deprecated under HTML 4.0, but you used it because it works
and because it has one of the most easily demonstrable visual effects on a web page.
The Node Object
You now have your element or elements from the web page, but what happens if you want to move
through your page systematically, from element to element or from attribute to attribute? This is where
you need to step back to a lower level. To move among elements, attributes, and text, you have to move
among nodes in your tree structure. It doesn't matter what is contained within the node, or rather, what
sort of node it is. This is why you need to go back to one of the objects of the core DOM specifi cation.
Your whole tree structure is made up of these base-level Node objects.
The Node Object: Navigating the DOM
The following table lists some common properties of the Node object that provide information about the
node, whether it is an element, attribute, or text, and enable you to move from one node to another.
Properties of the Node Object
Description of Property
firstChild
Returns the fi rst child node of an element
lastChild
Returns the last child node of an element
previousSibling
Returns the previous child node of an element at the same level
as the current child node
nextSibling
Returns the next child node of an element at the same level as
the current child node
Search WWH ::




Custom Search