15.02.2013 Views

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

22 <strong>JavaScript</strong> <strong>Examples</strong> <strong>Bible</strong>: The Essential Companion to <strong>JavaScript</strong> <strong>Bible</strong><br />

Example<br />

The following simplified function accepts a parameter that can be any object in a<br />

document hierarchy. The script finds out the reference of the object’s containing<br />

document for further reference to other objects:<br />

function getCompanionFormCount(obj) {<br />

var ownerDoc = obj.document<br />

return ownerDoc.forms.length<br />

}<br />

Because the ownerDoc variable contains a valid reference to a document object, the<br />

return statement uses that reference to return a typical property of the document<br />

object hierarchy.<br />

firstChild<br />

lastChild<br />

elementObject.firstChild<br />

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5<br />

Compatibility ✓ ✓ ✓<br />

Example<br />

These two properties come in handy for Listing 15-10, whose job it is to either<br />

add or replace LI elements to an existing OL element. You can enter any text you<br />

want to appear at the beginning or end of the list. Using the firstChild and<br />

lastChild properties simplifies access to the ends of the list. For the functions<br />

that replace child nodes, the example uses the replaceChild() method.<br />

Alternatively for IE4+, you can modify the innerText property of the objects<br />

returned by the firstChild or lastChild property. This example is especially<br />

interesting to watch when you add items to the list: The browser automatically<br />

renumbers items to fit the current state of the list.<br />

Listing 15-10: Using firstChild and lastChild Properties<br />

<br />

<br />

firstChild and lastChild Properties<br />

<br />

// helper function for prepend() and append()<br />

function makeNewLI(txt) {<br />

var newItem = document.createElement(“LI”)<br />

newItem.innerHTML = txt<br />

return newItem<br />

}<br />

function prepend(form) {<br />

var newItem = makeNewLI(form.input.value)<br />

var firstLI = document.getElementById(“myList”).firstChild<br />

document.getElementById(“myList”).insertBefore(newItem, firstLI)

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

Saved successfully!

Ooh no, something went wrong!