↑
Main Page
Ranges in Internet Explorer
Clean up
When you are done using a range, it is best to call the
detach()
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
detach()
ensures that it isn’t
taking up any more memory than necessary:
oRange.detach();
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
createTextRange()
on a
<body/>
,
<button/>
,
<input/>
, or
<textarea/>
element (not on the
document
itself):
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
findText()
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
Hello
, you can use the following code:
var oRange = document.body.createTextRange();
var bFound = oRange.findText(“Hello”);
After the second line of code, the text
Hello
is contained within the range. You can test this by using the
range’s
text
property (which returns the text contained in the range) or checking the returned value of
findText()
, which is true if the text was found:
alert(bFound);
alert(oRange.text);
To move the range through the document, you can use the second parameter of the
findText()
method,
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
Hello
in a document, you could use this code:
var bFound = oRange.findText(“Hello”);
var bFoundAgain = oRange.findText(“Hello”, 1);
329
Advanced DOM Techniques
13_579088 ch10.qxd 3/28/05 11:39 AM Page 329
Free JavaScript Editor
Ajax Editor
©
→