test(els[i].className))a.push(els[i]);
className is a property of an element and stores the value of the class attribute. You test
that against the regular expression, which returns true if it matches. If it??™s true, add the current
element into the array.
Finally, after you??™re done, pass back the array of elements:
return a;
CHAPTER 2 n HTML, CSS, AND JAVASCRIPT 30
Moving Around the DOM
After you retrieve a particular element, you often have to move around the DOM. There are
four ways to do this:
childNodes: As you saw earlier, childNodes enables you to retrieve all nodes under the current
element.
parentNode: Retrieves the direct parent of the current element.
nextSibling/previousSibling: Retrieves the next or previous node, respectively.
firstChild/lastChild: Retrieves the first or last child node of the current element.
Working Around Text Nodes
The way browsers handle text nodes can make moving around the DOM a little complicated.
Take the following code example:
Some text.
Some more text.
It might seem to make sense that the
has two childNodes; in IE, that??™s exactly what
you get. In all the other major browsers, however, it counts the whitespace between tags as a
node. As a result, you??™ll get five childNodes instead of just two. You??™ll need to take this into
account when navigating from element to element by checking to see whether the node you??™re
on is a text node or not.
Pages:
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77