Main Page

Ranges in Internet Explorer

Clean up
When you are done using a range, it is best to call the
method to free up system resources.
This isn’t required because dereferenced ranges are picked up by the garbage collector eventually. If,
however, the range is used initially and then no longer required, calling
ensures that it isn’t
taking up any more memory than necessary:
Ranges in Internet Explorer
Internet Explorer has a non-standard way of dealing with ranges, which can nonetheless be very effec-
tive as long as you understand the differences.
To begin, ranges in IE are called
text ranges
because they are intended primarily to deal with text (not
specifically DOM nodes). To create a range, you must call
on a
, or
element (not on the
var oRange = document.body.createTextRange();
Creating a range in this way allows it to be used anywhere on the page (creating a range on one of the
other specified elements limits the range to working on that element).
Simple selection in IE ranges
The simplest way to select an area of the page is to use the
method of the range. This
method finds the first instance of a given text string and moves the range to surround it. Once again,
consider the following HTML code:
<p id=”p1”><b>Hello</b> World</p>
To select
, you can use the following code:
var oRange = document.body.createTextRange();
var bFound = oRange.findText(“Hello”);
After the second line of code, the text
is contained within the range. You can test this by using the
property (which returns the text contained in the range) or checking the returned value of
, which is true if the text was found:
To move the range through the document, you can use the second parameter of the
which is a number indicating the direction to continue searching: A negative number indicates that the
search should go backwards, whereas a positive number indicates that the search should go forward. So,
to find the first two instances of
in a document, you could use this code:
var bFound = oRange.findText(“Hello”);
var bFoundAgain = oRange.findText(“Hello”, 1);
Advanced DOM Techniques
13_579088 ch10.qxd 3/28/05 11:39 AM Page 329

JavaScript EditorFree JavaScript Editor     Ajax Editor