Main Page

Complex selection in IE ranges

The closest thing to the DOM’s
selectNode()
is IE’s
moveToElementText()
, which accepts a DOM
element as an argument and selects all the element’s text, including HTML tags:
var oRange = document.body.createTextRange();
var oP1 = document.getElementById(“p1”);
oRange.moveToElementText(oP1);
To test that this works, you can use the
htmlText
property, which returns all the HTML contained
within the range:
alert(oRange.htmlText);
Ranges in IE don’t have any other properties that are dynamically updated as the range selection changes,
although a
parentElement()
method behaves the same as the DOM’s
commonAncestorContainer
property:
var oCommonAncestor = oRange.parentElement();
Complex selection in IE ranges
One of the complex parts of complex range selection in IE is that you must use one of the simple methods
of selection first. After the range is in a relatively correct position, you can use
move()
,
moveStart()
,
moveEnd()
, and
expand()
to further position the range.
Each of these methods accepts two arguments: the type of units to move and the number of units to
move. The type of units to move is one of the following string values:
?
“character” — Moves a point by one character
?
“word” — Moves a point by one word (a sequence of non-whitespace characters)
?
“sentence” — Moves a point by one sentence (a sequence of characters ending with a period,
question mark, or exclamation point)
?
“textedit” — Moves a point to the start or end of the current range selection
The
moveStart()
method moves the starting point of the range by the given number of units, whereas
the
moveEnd()
method moves the endpoint of the range by the given number of units:
oRange.moveStart(“word”, 2); //move the start point by two words
oRange.moveEnd(“character”, 1); //move the ending point by two words
You can also use the
expand()
method to normalize the range. The
expand()
method makes sure that
any partially selected units become fully selected. For example, if you selected only the middle two char-
acters of a word, you can call
expand(“word”)
to ensure that the entire word is enclosed by the range.
The
move()
method first collapses the range (making the start and end point equal) and then moves the
range by the specified number of units:
oRange.move(“character”, 5); //move over five characters
After using
move()
, you must use either
moveEnd()
to once again make a selection.
330
Chapter 10
13_579088 ch10.qxd 3/28/05 11:39 AM Page 330


JavaScript EditorFree JavaScript Editor     Ajax Editor


©