SEARCH
0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Prev | Current Page 66 | Next

Jonathan Snook, Aaron Gustafson, Stuart Langridge, and Dan Webb

"Accelerated DOM Scripting with Ajax, APIs, and Libraries"

For example:
var el = document.getElementById('node');
// grab the first element
var firstElement = el.childNodes[0];
if(firstElement.nodeType != 1) firstElement = el.childNodes[1];
If the first element turns out not to be an element type, grab the next node. I??™m making
the assumption here that there is only the text node between the opening tag and the first
element. Comment nodes can throw a wrench into the works. If that??™s the case, creating a
reusable function such as the following might be advantageous:
function getElement(node)
{
while(node && node.nodeType !=1)
{
node = node.nextSibling;
}
return node;
}
CHAPTER 2 n HTML, CSS, AND JAVASCRIPT 31
If the node passed in is an element, it skips the while loop altogether. Otherwise, it continues
to loop until it finds a node that is an element or until it finds no more nodes (in that
case, it returns null).
You can now rewrite the example like so:
var el = document.getElementById('node');
// grab the first element
var actualFirstElement = getElement(el.childNodes[0]);
This returns a consistent result across browsers.
nNote Whitespace in HTML includes the space, tab, line feed, form feed, and carriage return characters.
Although you can??™t see them, each of these characters takes up space in the file. As browsers render the
page, it should not render the whitespace of any text node that consists only of whitespace.


Pages:
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78