Main Page

Comparing DOM ranges

Comparing DOM ranges
If you have more than one range, you can use the
compareBoundaryPoints()
method to determine if
the ranges have any boundaries (start or end) in common. The method accepts two arguments: the range
to compare to and how to compare, which is a constant value:
?
START_TO_START
(0) — Compares the starting point of the first range to the starting point of
the second
?
START_TO_END
(1) — Compares the starting point of the first range to the end point of the
second
?
END_TO_END
(2) — Compares the end point of the first range to the end point of the second.
?
END_TO_START
(3) — Compares the end point of the first range to the start point of the second
The
compareBoundaryPoints()
method returns –1 if the point from the first range comes before the
point from the second range, 0 if the points are equal, or 1 if the point from the first range comes after
the point from the second range.
For example:
var oRange1 = document.createRange();
var oRange2 = document.createRange();
var oP1 = document.getElementById(“p1”);
oRange1.selectNodeContents(oP1);
oRange2.selectNodeContents(oP1);
oRange2.setEndBefore(oP1.lastChild);
alert(oRange1.compareBoundaryPoints(Range.START_TO_START, oRange2)); //outputs 0
alert(oRange1.compareBoundaryPoints(Range.END_TO_END, oRange2)); //outputs 1;
In this code, the starting points of the two ranges are exactly the same because both use the default value
from
selectNodeContents()
; therefore, the method returns 0. For
oRange2
, however, the end point is
changed using
setEndBefore()
, making the end point of
oRange1
come after the end point of
oRange2
(see Figure 10-7), so the method returns 1.
Figure 10-7
Cloning DOM ranges
If you find the need, you can duplicate any range by calling the
cloneRange()
method. This method
creates an exact duplicate of the range on which it is called:
var oNewRange = oRange.cloneRange();
The new range contains all of the same properties as the original and can be modified without affecting
the original in any way.
<p id="pl"><b>Hello</b> World</p>
oRange2
oRange1
328
Chapter 10
13_579088 ch10.qxd 3/28/05 11:39 AM Page 328


JavaScript EditorFree JavaScript Editor     Ajax Editor


©