HTML and CSS Reference
In-Depth Information
Traversing the Document The final step is to bind the event that toggles the display
of the answers to each of the questions. This is the most complex bit of code on the page.
First, let me explain how the event handler works:
function() {
currentNode = this.nextSibling;
while (currentNode) {
if (currentNode.nodeType == “1” && currentNode.tagName == “DD”) {
if (currentNode.style.display == 'none') {
currentNode.style.display = 'block';
}
else {
currentNode.style.display = 'none';
}
break;
}
currentNode = currentNode.nextSibling;
}
return false;
};
That's the function that will be used as the onclick handler for each of the questions. As
you may remember, in the context of an event handler, this is the element associated
with the event. The main challenge in this function is locating the answer associated with
the question the user clicked on and displaying it.
To do so, the function will navigate through the DOM to find the next DD element in the
DOM tree following the DT element that the user clicked on. First, I use the
nextSibling property of this , and then I start a while loop that will iterate over each of
the siblings of that element. The while condition ensures that the loop will run until this
runs out of siblings.
The nextSibling property is a reference to the next node in the DOM tree. A node is
different from an element. HTML elements are nodes, but the whitespace between tags is
a node, as is the text inside a tag. So the nextSibling of a node might very well be the
return character at the end of the line following the tag. There are a number of other
properties associated with nodes as well that can be used to traverse the document. Some
are listed in Table 15.2.
TABLE 15.2
Node Properties for Navigating the DOM
Method
Description
An array of all the children of a node.
childNodes
The first child node of a node.
firstChild
The markup and content inside a node. You can set this property
to change the contents of a node.
innertHTML
 
 
Search WWH ::




Custom Search