↑
Main Page
Inserting DOM range content
extractContents()
is similar to
deleteContents()
. It also removes the range selection from the
document and returns the range’s document fragment as the function value. This allows you to insert
the contents of the range somewhere else:
var oP1 = document.getElementById(“p1”);
var oHello = oP1.firstChild.firstChild;
var oWorld = oP1.lastChild;
var oRange = document.createRange();
oRange.setStart(oHello, 2);
oRange.setEnd(oWorld, 3);
var oFragment = oRange.extractContents();
document.body.appendChild(oFragment);
In this example, the fragment is extracted and added to the end of the document’s
<body/>
element
(remember, when a document fragment is passed into
appendChild()
, only the fragment’s children are
added, not the fragment itself). What you see in this example is the code
<b>He</b>rld
at the top of the
page, and
<b>llo</b> Wo
at the bottom of the page.
Another option is to leave the fragment in place, but create a clone of it that can be inserted elsewhere in
the document by using
cloneContents()
:
var oP1 = document.getElementById(“p1”);
var oHello = oP1.firstChild.firstChild;
var oWorld = oP1.lastChild;
var oRange = document.createRange();
oRange.setStart(oHello, 2);
oRange.setEnd(oWorld, 3);
var oFragment = oRange.cloneContents();
document.body.appendChild(oFragment);
This method is very similar to
deleteContents()
because both return the range’s document fragment.
This results in
<b>llo</> Wo
being added to the end of the page; the original HTML code remains intact.
Inserting DOM range content
The previous three methods all dealt with removing information from the range in one way or another.
It is also possible to add content to the range using a couple of different methods.
The
insertNode()
method enables you to insert a node at the beginning of the selection. Suppose you
wanted to insert the following HTML code into the range defined in the previous section:
<span style=”color: red”>Inserted text</span>
The document fragment and accompanying changes to the range selection do not
happen until one of these methods is called. The original HTML remains intact right
up until that point.
325
Advanced DOM Techniques
13_579088 ch10.qxd 3/28/05 11:39 AM Page 325
Free JavaScript Editor
Ajax Editor
©
→