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.

Chapter 1 ✦ Generic HTML Element Objects (Chapter 15)<br />

All characters of the text fragment, including spaces, are replaced. Therefore,<br />

you may need to supply a trailing space, as shown here, if the fragment you replace<br />

has a space.<br />

document.all.myP.replaceAdjacentText(“beforeEnd”, “ good people.”)<br />

This is another way to replace the text fragment following the myEM element, but<br />

it is also relative to the surrounding myP element. If you now attempt to replace text<br />

after the end of the myP block-level element,<br />

document.all.myP.replaceAdjacentText(“afterEnd”, “Hooray!”)<br />

the text fragment is inserted after the end of the myP element’s tag set. The fragment<br />

is just kind of floating in the document object model as an unlabeled text node.<br />

replaceChild(newNodeObject, oldNodeObject)<br />

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

Compatibility ✓ ✓ ✓<br />

Example<br />

You can see an example of replaceChild() as part of Listing 15-21 earlier in<br />

this chapter.<br />

replaceNode(“newNodeObject”)<br />

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

Compatibility ✓ ✓<br />

Example<br />

Listing 15-31 demonstrates three node-related methods: removeNode(),<br />

replaceNode(), and swapNode(). These methods work in IE5+ only.<br />

The page rendered from Listing 15-31 begins with a UL type list of four items. Four<br />

buttons control various aspects of the node structure of this list element. The first<br />

button invokes the replace() function, which changes the UL type to OL. To do this,<br />

the function must temporarily tuck away all child nodes of the original UL element so<br />

that they can be added back into the new OL element. At the same time, the old UL<br />

node is stored in a global variable (oldNode) for restoration in another function.<br />

To replace the UL node with an OL, the replace() function creates a new, empty<br />

OL element and assigns the myOL ID to it. Next, the children (LI elements) are stored<br />

en masse as an array in the variable innards. The child nodes are then inserted into<br />

the empty OL element, using the insertBefore() method. Notice that as each<br />

child element from the innards array is inserted into the OL element, the child element<br />

is removed from the innards array. That’s why the loop to insert the child<br />

nodes is a while loop that constantly inserts the first item of the innards array to<br />

87<br />

elementObject.replaceNode()

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

Saved successfully!

Ooh no, something went wrong!