Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
32 CHAPTER 2 s HTML, CSS, AND JAVASCRIPT If the node passed in is an element, it skips the while loop altogether. Otherwise, it con- tinues 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. s Note 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. Browsers also collapse multiple whitespace characters into a single space, except in <pre> tags. Whitespace between the opening tag and the first non-whitespace character should be ignored. Although rendering whitespace is consistent across browsers, what happens when you retrieve it via JavaScript isn't consistent. If you need consistency in all browsers when manipulating text nodes, you need to normalize the string by trimming all whitespace characters at the beginning and end of the string, along with replacing any nonspaces with spaces and then compressing multiple spaces into a single space.