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.

extractContents()<br />

Chapter 5 ✦ Body Text Objects (Chapter 19)<br />

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

Compatibility ✓<br />

Example<br />

When Netscape outfits the NN6 browser with the extractContents() method,<br />

use The Evaluator (Chapter 13 in the <strong>JavaScript</strong> <strong>Bible</strong>) to see how the method<br />

works. Begin by creating a new range object that contains the text of the myP paragraph<br />

element.<br />

a = document.createRange()<br />

a.selectNode(document.getElementById(“myP”))<br />

Next, extract the original range’s content and preserve the copy in variable b:<br />

b = a.extractContents()<br />

Move the original range so that it is an insertion point at the end of the body by<br />

first expanding it to encompass the entire body and then collapse it to the end<br />

a.selectNode(document.body)<br />

a.collapse(false)<br />

Now, insert the extracted fragment at the very end of the body:<br />

a.insertNode(b)<br />

If you scroll to the bottom of the page, you see a copy of the text.<br />

insertNode(nodeReference)<br />

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

Compatibility ✓<br />

Example<br />

Listing 19-5, which relies on selection and Range object features not implemented<br />

in the first release of NN6, demonstrates the insertNode() method plus<br />

some additional items from the NN6 selection object. The example even includes<br />

a rudimentary undo buffer for scripted changes to a text range. In the page generated<br />

by this listing, users can select any text in a paragraph and have the script<br />

automatically convert the text to all uppercase characters. The task of replacing a<br />

selection with other text requires several steps, starting with the selection, which is<br />

retrieved via the window.getSelection() method. After making sure the selection<br />

contains some text (that is, the selection isn’t collapsed), the selection is preserved<br />

as a range object so that the starting text can be stored in a global variable (as a<br />

285<br />

Range.insertNode()

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

Saved successfully!

Ooh no, something went wrong!