Java Reference
In-Depth Information
pElement = h1Element.nextSibling;
}
else
{
pElement = h1Element.nextSibling.nextSibling;
}
pElement.style.color = “red”;
</script>
</body>
</html>
This code demonstrates a fundamental difference between IE's DOM and the DOM present in other
browsers. Firefox's, Safari's, Chrome's, and Opera's DOM treat everything as a node in the DOM
tree, including the whitespace between elements. On the other hand, IE strips out this unnecessary
whitespace. So to locate the
<p/>
element in the previous example, a sibling to the
<h1/>
element, it is
required to check the next sibling's
nodeType
property. An element's node type is
1
(text nodes are
3
).
If the
nextSibling
's
nodeType
is
1
, then you assign that sibling's reference to
pElement
. If not, you get
the next sibling (the
<p/>
element) of
h1Element
's sibling (the whitespace text node).
In effect, you are navigating through the tree structure as shown in Figure 12-8.
<BODY>
<H1>
<P>
'My Heading'
'This is
some text in
a paragraph'
Figure 12-8
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.
<!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>example</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 pElement = document.getElementById(“paragraph1”);