04.11.2015 Views

javascript

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

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

Chapter 11: DOM Levels 2 and 3<br />

The first method is the simplest to understand and use: deleteContents() . This method simply<br />

deletes the contents of the range from the document. Here is an example:<br />

var p1 = document.getElementById(“p1”);<br />

var helloNode = p1.firstChild.firstChild;<br />

var worldNode = p1.lastChild;<br />

var range = document.createRange();<br />

range.setStart(helloNode, 2);<br />

range.setSend(worldNode, 3);<br />

range.deleteContents();<br />

Executing this code results in the following HTML being shown on the page:<br />

< p > < b > He < /b > rld! < /p ><br />

Since the range selection process altered the underlying DOM structure to remain well formed, the<br />

resulting DOM structure is well formed even after removing the contents.<br />

extractContents() is similar to deleteContents() in that it also removes the range selection from<br />

the document. The difference is that extractContents() returns the range ’ s document fragment as the<br />

function value. This allows you to insert the contents of the range somewhere else. Here is an example:<br />

var p1 = document.getElementById(“p1”);<br />

var helloNode = p1.firstChild.firstChild;<br />

var worldNode = p1.lastChild;<br />

var range = document.createRange();<br />

range.setStart(helloNode, 2);<br />

range.setEnd(worldNode, 3);<br />

var fragment = range.extractContents();<br />

p1.parentNode.appendChild(fragment);<br />

In this example, the fragment is extracted and added to the end of the document ’ s < body > element.<br />

(Remember, when a document fragment is passed into appendChild() , only the fragment ’ s children are<br />

added, not the fragment itself.) The resulting HTML is as follows:<br />

< p > < b > He < /b > rld! < /p ><br />

< b > llo < /b > Wo<br />

Another option is to leave the range in place but create a clone of it that can be inserted elsewhere in the<br />

document by using cloneContents() , as shown in this example:<br />

var p1 = document.getElementById(“p1”);<br />

var helloNode = p1.firstChild.firstChild;<br />

var worldNode = p1.lastChild;<br />

var range = document.createRange();<br />

range.setStart(helloNode, 2);<br />

354

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

Saved successfully!

Ooh no, something went wrong!