04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

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

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

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

This method is very similar to extractContents() because both return a document fragment. The<br />

main difference is that the document fragment returned by cloneContents() contains clones of<br />

the nodes contained in the range instead of the actual nodes. With this operation, the HTML in the page<br />

is as follows:<br />

< p > < b > Hello < /b > World! < /p ><br />

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

It ’ s important to note the splitting of nodes to ensure that a well - formed document isn ’ t produced until<br />

one of these methods is called. The original HTML remains intact right up until the point that the DOM<br />

is modified.<br />

Inserting DOM Range Content<br />

Ranges can be used to remove or clone content, as seen in the previous section, as well as to manipulate<br />

the contents inside of the range. The insertNode() method enables you to insert a node at the<br />

beginning of the range selection. As an example, suppose that you want to insert the following HTML<br />

prior to the HTML used in the previous example:<br />

< span style=”color: red” > Inserted text < /span ><br />

The following code accomplishes this:<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 span = document.createElement(“span”);<br />

span.style.color = “red”;<br />

span.appendChild(document.createTextNode(“Inserted text”));<br />

range.insertNode(span);<br />

Running this JavaScript effectively creates the following HTML code:<br />

< p id=”p1” > < b > He < span style=”color: red” > Inserted text < /span > llo < /b > World < /p ><br />

Note that < span > is inserted just before the “ llo ” in “ Hello ” , which is the first part of the range<br />

selection. Also note that the original HTML didn ’ t add or remove < b > elements because none of the<br />

methods introduced in the previous section was used. You can use this technique to insert helpful<br />

information, such as an image next to links that open in a new window.<br />

355

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

Saved successfully!

Ooh no, something went wrong!