15.02.2013 Views

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

SHOW MORE
SHOW LESS

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

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

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

The append() function creates a new LI element and then uses the<br />

appendChild() method to attach the text box text as the displayed text for the<br />

item. The nested expression, document.createTextNode(form.input.value),<br />

evaluates to a legitimate node that is appended to the new LI item. All of this occurs<br />

before the new LI item is added to the document. In the final statement of the function,<br />

appendChild() is invoked from the vantage point of the UL element — thus<br />

adding the LI element as a child node of the UL element.<br />

Invoking the replaceChild() method in the replace() function utilizes some<br />

of the same code. The main difference is that the replaceChild() method requires<br />

a second parameter: a reference to the child element to be replaced. This demonstration<br />

replaces the final child node of the UL list, so the function takes advantage<br />

of the lastChild property of all elements to get a reference to that final nested<br />

child. That reference becomes the second parameter to replaceChild().<br />

Listing 15-21: Various Child Methods<br />

<br />

<br />

appendChild(), removeChild(), and replaceChild() Methods<br />

<br />

function append(form) {<br />

if (form.input.value) {<br />

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

newItem.appendChild(document.createTextNode(form.input.value))<br />

document.getElementById(“myUL”).appendChild(newItem)<br />

}<br />

}<br />

function replace(form) {<br />

if (form.input.value) {<br />

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

var lastChild = document.getElementById(“myUL”).lastChild<br />

newItem.appendChild(document.createTextNode(form.input.value))<br />

document.getElementById(“myUL”).replaceChild(newItem, lastChild)<br />

}<br />

}<br />

function restore() {<br />

var oneChild<br />

var mainObj = document.getElementById(“myUL”)<br />

while (mainObj.childNodes.length > 2) {<br />

oneChild = mainObj.lastChild<br />

mainObj.removeChild(oneChild)<br />

}<br />

}<br />

<br />

<br />

<br />

Child Methods<br />

<br />

Here is a list of items:<br />

First Item<br />

elementObject.appendChild()

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

Saved successfully!

Ooh no, something went wrong!