↑
Main Page
Comparing IE ranges
Comparing IE ranges
Ranges in IE have a similar capability to the DOM range’s
compareBoundaryPoints()
method called
compareEndPoints()
. This method accepts two arguments: the type of comparison and the range to
compare to. Unlike the DOM implementation, the type of comparison in IE is one of the following
strings: “StartToStart”, “StartToEnd”, “EndToEnd”, and “EndToStart”. These comparisons are identically
equal to the comparable ones in DOM ranges.
Also similar to the DOM,
compareEndPoints()
returns –1 if the first range boundary occurs before the
second range’s boundary, 0 if they are equal, and 1 if the first range boundary occurs after the second
range boundary. Once again, consider using the Hello World HTML code from the previous example.
The following code creates two ranges, one that selects
“Hello World”
(including the
<b/>
tags) and
one that selects
“Hello”
(also including the
<b/>
tags, see Figure 10-7):
var oRange1 = document.body.createTextRange();
var oRange2 = document.body.createTextRange();
oRange1.findText(“Hello World”);
oRange2.findText(“Hello”);
alert(oRange1.compareEndPoints(“StartToStart”, oRange2)); //outputs 0
alert(oRange1.compareEndPoints(“EndToEnd”, oRange2)); //outputs 1;
Similar to the example in “Comparing DOM Ranges,” the first and second range share the same starting
point, so
compareEndPoints()
returns 1;
oRange1
’s end point occurs after
oRange2
’s endpoint, so
compareEndPoints()
returns 1.
IE also has two additional methods for comparing ranges:
isEqual()
, which determines if two ranges
are identically equal, and
inRange()
, which determines if a range occurs inside of another range:
var oRange1 = document.body.createTextRange();
var oRange2 = document.body.createTextRange();
oRange1.findText(“Hello World”);
oRange2.findText(“Hello”);
alert(“oRange1.isEqual(oRange2): “ + oRange1.isEqual(oRange2)); //outputs “false”
alert(“oRange1.inRange(oRange2): “ + oRange1.inRange(oRange2)); //outputs “true”
This example uses the same ranges as in the previous example to illustrate these methods. You already
know that the ranges are not equal because the end points are different; to be equal, the ranges must
share both start and end points. So the first alert displays
“false”
. However,
oRange2
is actually inside
of
oRange1
, because its end point occurs before
oRange1
’s end point but after
oRange1
’s start point. For
this reason, the second alert displays
“true”
, telling you
oRange2
is in
oRange1
.
Cloning an IE range
Similar to the DOM, it is possible to create exact duplicates (clones) of a given range by calling the
duplicate()
method:
var oNewRange = oRange.duplicate();
All properties from the original range are carried over into the newly created one.
332
Chapter 10
13_579088 ch10.qxd 3/28/05 11:39 AM Page 332
Free JavaScript Editor
Ajax Editor
©
→