06.07.2017 Views

Mastering JavaScript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 8<br />

// run this function when the document is loaded<br />

window.onload = function() {<br />

var doc = document.documentElement;<br />

var body = doc.body;<br />

var _head = doc.firstChild;<br />

var _body = doc.lastChild;<br />

var _head_ = doc.childNodes[0];<br />

var title = _head.firstChild;<br />

alert(_head.parentNode === doc); //true<br />

}<br />

<br />

<br />

<br />

Hello World!<br />

<br />

<br />

The anonymous function is executed when the browser loads the page. In the<br />

function, we are getting the nodes of the DOM programmatically. The entire HTML<br />

document can be accessed using the document.documentElement function. We<br />

store the document in a variable. Once the document is accessed, we can traverse the<br />

nodes using several helper properties of the document. We are accessing the <br />

element using doc.body. You can traverse through the children of an element using<br />

the childNodes array. The first and last children of a node can be accessed using<br />

additional properties—firstChild and lastChild.<br />

It is not recommended to use render-blocking <strong>JavaScript</strong> in the <br />

tag. This slows down the page render dramatically. Modern browsers<br />

support the async and defer attributes to indicate to the browsers<br />

that the rendering can go on while the script is being downloaded.<br />

You can use these tags in the tag without worrying about<br />

performance degradation. You can get more information at http://<br />

stackoverflow.com/questions/436411/where-is-the-bestplace-to-put-script-tags-in-html-markup.<br />

Accessing specific nodes<br />

The core DOM defines the getElementsByTagName() method to return NodeList<br />

of all the element objects whose tagName property is equal to a specific value. The<br />

following line of code returns a list of all the elements in a document:<br />

var paragraphs = document.getElementsByTagName('p');<br />

[ 183 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!