Main Page

Interacting with DOM range content

Interacting with DOM range content
When a range is created, internally it creates a document fragment node onto which all the nodes in the
selection are attached. Before this can happen, however, the range must make sure that the selection is
well-formed.
You just learned that it is possible to select the entire area from the first letter
l
in
Hello
to the
o
in
World
, including the
</b>
end tag (see Figure 10-4). This would be impossible using the normal DOM
methods described earlier in the book.
Figure 10-4
The reason a range can get away with this trick is that it recognizes missing opening and closing tags.
In the previous example, the range calculates that a
<b>
start tag is missing inside the selection, so the
range dynamically adds it behind the scenes, along with a new
</b>
end tag to enclose
H
e
, thus altering
the DOM to the following:
<p><b>He</b><b>llo</b> World</p>
The document fragment contained within the range is displayed in Figure 10-5.
Figure 10-5
With the document fragment created, you can manipulate the contents of the range using a variety of
methods.
The first method is the simplest to understand and use:
deleteContents()
. This method simply deletes
the contents of the range from the document. In the previous example, calling
deleteContents()
on the
range leaves this HTML in the page:
<p><b>He</b>rld</p>
Because the entire document fragment is removed, the range is kind enough to place the missing
</b>
tag into the document so it remains well-formed.
llo
<b/>
DocumentFragment
Wo
<p><b>Hello</b> World</p>
Range
324
Chapter 10
13_579088 ch10.qxd 3/28/05 11:39 AM Page 324


JavaScript EditorFree JavaScript Editor     Ajax Editor


©