Main Page

Collapsing a DOM Range

Collapsing a DOM Range
To empty a range, (that is, to have it select no part of the document), you
it. Collapsing a range
resembles the behavior of a text box. When you have text in a text box, you can highlight an entire word
using the mouse. However, if you left-click the mouse again, the selection is removed and the cursor is
located between two letters. When you collapse a range, you are setting its locations between parts of a
document, either at the beginning of the range selection or at the end. Figure 10-6 illustrates what hap-
pens when a range is collapsed.
Figure 10-6
You can collapse a range by using the
method, which accepts a single argument: a Boolean
value indicating which end of the range to collapse to. If the argument is
, then the range is col-
lapsed to its starting point; if
, the range is collapsed to its ending point. To determine if a range is
collapsed, you can use the
oRange.collapse(true); //collapse to the starting point
alert(oRange.collapsed); //outputs “true”
Testing whether a range is collapsed is helpful if you aren’t sure if two nodes in the range are next to
each other. For example, consider this HTML code:
<p id=”p1”>Paragraph 1</p><p id=”p2”>Paragraph 2</p>
If you don’t know the exact makeup of this code (because, perhaps, it is automatically generated), you
might try creating a range like this:
var oP1 = document.getElementById(“p1”);
var oP2 = document.getElementById(“p2”);
var oRange = document.createRange();
alert(oRange.collapsed); //outputs “true”
In this case, the created range is collapsed because there is nothing between the end of
and the begin-
ning of
<p><b>Hello</b> World</p>
Original Range
<p><b>Hello</b> World</p>
Collapsed to beginning
<p><b>Hello</b> World</p>
Collapsed to end
Advanced DOM Techniques
13_579088 ch10.qxd 3/28/05 11:39 AM Page 327

JavaScript EditorFree JavaScript Editor     Ajax Editor