04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 10: The Document Object Model<br />

This example shows that the values of documentElement , firstChild , and childNodes[0] are all the<br />

same — all three point to the < html > element.<br />

As an instance of HTMLDocument , the document object also has a body property that points to the<br />

< body > element directly. Since this is the element most often used by developers, document.body tends<br />

to be used quite frequently in JavaScript, as this example shows:<br />

var body = document.body; //get reference to < body ><br />

Both document.documentElement and document.body are supported in all major browsers.<br />

Another possible child node of a Document is a DocumentType . The < !DOCTYPE > tag is considered to be<br />

a separate entity from other parts of the document, and its information is accessible through the<br />

doctype property ( document.doctype in browsers) as shown here:<br />

var doctype = document.doctype; //get reference to < !DOCTYPE ><br />

Browser support for document.doctype varies considerably, as described here:<br />

IE — A document type, if present, is misinterpreted as a comment and treated as<br />

a Comment node. document.doctype is always null .<br />

Firefox — A document type, if present, is the first child node of the document. document<br />

.doctype is a DocumentType node, and the same node is accessible via document.firstChild<br />

or document.childNodes[0] .<br />

Safari, Chrome, and Opera — A document type, if present, is parsed but is not considered a<br />

child node of the document. document.doctype is a DocumentType node, but the node does<br />

not appear in document.childNodes .<br />

Due to the inconsistent browser support for document.doctype , it is of limited usefulness.<br />

Comments that appear outside of the < html > element are, technically, child nodes of the document.<br />

Once again, browser support varies greatly as to whether these comments will be recognized and<br />

represented appropriately. Consider the following HTML page:<br />

< !-- first comment -- ><br />

< html ><br />

< body ><br />

< /body ><br />

< /html ><br />

< !-- second comment -- ><br />

This page seems to have three child nodes: a comment, the < html > element, and another comment.<br />

Logically, you would expect document.childNodes to have three items corresponding to what appears<br />

in the code. In practice, however, browsers handle comments outside of the < html > element in the<br />

following very different ways:<br />

270

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!