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 5 ✦ Body Text Objects (Chapter 19)<br />

<br />

<br />

<br />

Lorem ipsum dolor sit, consectetaur adipisicing<br />

elit,<br />

sed do eiusmod tempor incididunt ut labore et dolore aliqua. Ut enim adminim<br />

veniam,<br />

quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo<br />

consequat.<br />

<br />

<br />

createContextualFragment(“text”)<br />

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

Compatibility ✓<br />

Example<br />

Use The Evaluator (Chapter 13 in the <strong>JavaScript</strong> <strong>Bible</strong>) to create a document fragment<br />

and replace an existing document tree node with the fragment. Begin by creating<br />

the range and fragment:<br />

a = document.createRange()<br />

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

b = a.createContextualFragment(“a bunch of<br />

”)<br />

This fragment consists of a SPAN element node with a text node nested inside. At<br />

this point, you can inspect the properties of the document fragment by entering b<br />

into the bottom text box.<br />

To replace the myEM element on the page with this new fragment, use the<br />

replaceChild() method on the enclosing myP element:<br />

document.getElementById(“myP”).replaceChild(b, document.getElementById(“myEM”))<br />

The fragment now becomes a legitimate child node of the myP element and can be<br />

referenced like any node in the document tree. For example, if you enter the following<br />

statement into the top text box of The Evaluator, you can retrieve a copy of the<br />

text node inside the new SPAN element:<br />

document.getElementById(“myP”).childNodes[1].firstChild.nodeValue<br />

283<br />

Range.createContextualFragment()

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

Saved successfully!

Ooh no, something went wrong!