Java Reference
In-Depth Information
<title></title>
</head>
<body>
<h1 id="heading1">My Heading</h1>
<p id="paragraph1">This is some text in a paragraph</p>
<script>
var h1Element = document.getElementById("heading1");
h1Element.style.color = "red";
</script>
</body>
</html>
You can now use h1Element to navigate your tree structure and make whatever changes you desire.
The following code uses h1Element as a starting point to find the <p/> element and change its text
color:
<!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 h1Element = document.getElementById("heading1");
h1Element.style.color = "red";
var pElement;
if (h1Element.nextSibling.nodeType == 1) {
pElement = h1Element.nextSibling;
} else {
pElement = h1Element.nextSibling.nextSibling;
}
pElement.style.color = "red";
</script>
</body>
</html>
This code demonstrates a fundamental difference between the DOM present in modern browsers
and that in older versions of IE. The DOM in modern browsers treats everything as a node in
the DOM tree, including the whitespace between elements. On the other hand, older versions of
IE strip out this whitespace. So to locate the <p/> element in the previous example, a sibling to
the <h1/> element, you must 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 , 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 9-8.
Search WWH ::




Custom Search