HTML and CSS Reference
In-Depth Information
Method
Description
The last child of a node.
lastChild
The next sibling of the node (at the same level of the DOM tree).
nextSibling
The parent of the current node.
parentNode
15
The node that precedes the current node at the same level of
the tree.
previousSibling
All the properties in the table are
null
if it's not possible to traverse the DOM in that
direction. For example, if a node has no child nodes, its
lastChild
property will be
null
.
Here's what happens when a user clicks one of the questions. As mentioned, a
while
loop will iterate over the siblings of the question. Inside the while loop, I check the
nodeType
and
tagName
of the current node.
The
nodeType
property contains a number that identifies what type of node is being
processed. Element nodes have a node type of 1. Attributes are node type 2, and text
nodes are type 3. There are 12 total node types, but those three are the main ones you'll
use. In this function, I'm searching for the
<dd>
tag that follows the DT tag that contains
the question. I have to check the node type before checking the
tagName
property,
because only elements (which have node type 1) support the
tagName
property. If I didn't
check the node type first, other node types would cause errors.
Each sibling node that follows the original
<dt>
is tested, and as soon as a
<dd>
element
is found, the script toggles the visibility of that element. It then uses the
break
statement
to stop executing the loop. If the node is not a
<dd>
element, then the next sibling of
currentNode
is assigned to the
currentNode
variable, and the loop is executed again. If
the
<dd>
element is never found, then when there are no more siblings, the
currentNode
variable will be set to
null
, and execution of the loop will stop.
At the end, the function returns
false
:
questions = faqList.getElementsByTagName(“dt”);
for (i = 0; i < questions.length; i++) {
questions[i].onclick = function() {
// The actual event handling code goes here.
}
}
First, I use
getElementsByTagName()
to get a list of all the
<dt>
tags that are children of
faqList
. Then I used a
for
loop to iterate over them and bind the function described
previously to their
onclick
event.
▲