Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

Hiding and Showing Content 545

19


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 19.2.


TABLE 19.2 Node Properties for Navigating the DOM


Method Description


childNodes An array of all the children of a node.


firstChild The first child node of a node.


innerHTML The markup and content inside a node. You can set this property to
change the contents of a node.


lastChild The last child of a node.


nextSibling The next sibling of the node (at the same level of the DOM tree).


parentNode The parent of the current node.


previousSibling The node that precedes the current node at the same level of the tree.


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 pro-
cessed. 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

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 (that 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

is tested, and as soon as a
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
element, then the next sibling of cur-
rentNode is assigned to the currentNode variable, and the loop is executed again. If the


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.

Free download pdf