14.08.2016 Views

Beginning JavaScript with DOM Scripting and Ajax, 2nd Edition

Create successful ePaper yourself

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

Chapter 4 ■ HTML <strong>and</strong> <strong>JavaScript</strong><br />

while(parentElm.className != "dynamic")<br />

{<br />

parentElm = parentElm.parentNode;<br />

}<br />

However, this loop will end in an "TypeError: Cannot read property 'className' of null" error when there<br />

is no element <strong>with</strong> the right class. If you tell the loop to stop at the body, you can avoid that error:<br />

var myLinkItem = document.getElementById('linkedItem');<br />

var parentElm = myLinkItem.parentNode;<br />

while(!parentElm.className != 'dynamic'&& parentElm != document.body')<br />

{<br />

parentElm=parentElm.parentNode;<br />

}<br />

alert(parentElm);<br />

Among Siblings<br />

The family analogy continues <strong>with</strong> siblings, which are elements on the same level. (They don’t come in<br />

different genders like brothers or sisters, though.) You can reach a different child node on the same level via the<br />

previousSibling <strong>and</strong> nextSibling properties of a node. Let’s go back to our list example:<br />

<br />

List Item 1<br />

List Item 2<br />

<br />

<br />

Linked List Item<br />

<br />

<br />

List Item 4<br />

<br />

You can reach the link via getElementById() <strong>and</strong> the LI containing the link via parentNode. The properties<br />

previousSibling <strong>and</strong> nextSibling allow you to get List Item 2 <strong>and</strong> List Item 3, respectively:<br />

var myLinkItem = document.getElementById("linkedItem");<br />

var listItem = myLinkItem.parentNode;<br />

var nextListItem = myLinkItem.nextSibling;<br />

var prevListItem = myLinkItem.previousSibling;<br />

If the current object is the last child of the parent element, nextSibling will be undefined <strong>and</strong> cause an error if you<br />

don’t test for it properly. Unlike <strong>with</strong> childNodes, there are no shortcut properties for the first <strong>and</strong> last siblings, but you<br />

could write utility methods to find them. For example, suppose you want to find the first <strong>and</strong> the last LI in our demo HTML:<br />

document.addEventListener("<strong>DOM</strong>ContentLoaded",init,false);<br />

function init()<br />

{<br />

var myLinkItem=document.getElementById("linkedItem");<br />

var first=firstSibling(myLinkItem.parentNode);<br />

var last=lastSibling(myLinkItem.parentNode);<br />

85<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!