Java Reference
In-Depth Information
The same principles also work in reverse. You can go back
and change the code to navigate from the
<p/>
element to
the
<h1/>
element:
<body>
<h1>
<p>
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
</head>
<body>
<h1 id="heading1">My Heading</h1>
<p id="paragraph1">This is some text in a paragraph</p>
<script>
var pElement = document.getElementById("paragraph1");
pElement.style.color = "red";
“My Heading”
“This is
some text in
a paragraph”
figure 9-8
var h1Element;
if (pElement.previousSibling.nodeType == 1) {
h1Element = pElement.previousSibling;
} else {
h1Element = pElement.previousSibling.previousSibling;
}
h1Element.style.color = "red";
</script>
</body>
</html>
What you're doing here is the exact opposite; you find the
<p/>
by passing the value of its
id
attribute to the
getElementById()
method and storing the returned element reference to the
pElement
variable. You then find the correct previous sibling so that your code works in all
browsers, and you change its text color to red.
Navigating Your htML Document Using the DOM
trY it out
Up until now, you've been cheating, because you haven't truly navigated your HTML document. You've
just used
document.getElementById()
to return an element and navigated to different nodes from
there. Now let's use the
documentElement
property of the
document
object and do this properly. You'll
start at the top of your tree and move down through the child nodes to get at those elements; then
you'll navigate through your child nodes and change the properties in the same way as before.
Type the following into your text editor:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 9, Example 2</title>
</head>
<body>
<h1 id="heading1">My Heading</h1>