Java Reference
In-Depth Information
pElement.style.color = “red”;
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 fi nd the <p/> by passing the value of its id attribute
to the getElementById() method and storing the returned element reference to the pElement vari-
able. You then fi nd the correct previous sibling so that your code works in all browsers, and you change
its text color to red.
Try It Out Navigating Your HTML Document Using the DOM
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 PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>Chapter 12: Example 2</title>
</head>
<body>
<h1 id=”heading1”>My Heading</h1>
<p id=”paragraph1”>This is some text in a paragraph</p>
<script type=”text/javascript”>
var htmlElement; // htmlElement stores reference to <html>
var headElement; // headingElement stores reference to <head>
var bodyElement; // bodyElement stores reference to <body>
var h1Element; // h1Element stores reference to <h1>
var pElement; // pElement stores reference to <p>
htmlElement = document.documentElement;
headElement = htmlElement.firstChild;
alert(headElement.tagName);
if (headElement.nextSibling.nodeType == 3)
Search WWH ::




Custom Search