↑
Main Page
Complex selection in DOM ranges
?
setEndAfter(
refNode
)
— Sets the ending point of the range to begin before
refNode
(so
refNode
is the last node in the selection). The
endContainer
property is set to
refNode
’s par-
ent and the
endOffset
property is set to the index of
refNode
within its parent’s
childNodes
collection plus one.
Using any of these methods, all properties are assigned for you. However, it is possible to assign these
values directly in order to make complex range selections.
Complex selection in DOM ranges
Creating complex ranges requires the use of range
setStart()
and
setEnd()
methods. Both methods
accept two arguments: a reference node and an offset. For
setStart()
, the reference node becomes the
startContainer
, and the offset becomes the
startOffset
; for
setEnd()
, the reference node becomes
the
endContainer
, and the offset becomes the
endOffset
.
Using these methods, it is possible to mimic
selectNode()
and
selectNodeContents()
. For example,
the
useRanges()
function in the previous example can be rewritten using
setStart()
and
setEnd()
:
function useRanges() {
var oRange1 = document.createRange();
var oRange2 = document.createRange();
var oP1 = document.getElementById(“p1”);
var iP1Index = -1;
for (var i=0; i < oP1.parentNode.childNodes.length; i++) {
if (oP1.parentNode.childNodes[i] == oP1) {
iP1Index = i;
break;
}
}
oRange1.setStart(oP1.parentNode, iP1Index);
oRange1.setEnd(oP1.parentNode, iP1Index + 1);
oRange2.setStart(oP1, 0);
oRange2.setEnd(oP1, oP1.childNodes.length);
//textbox assignments here
}
Note that to select the node (using
oRange1
), you must first determine the index of the given node (
oP1
)
in its parent node’s
childNodes
collection. To select the node contents (using
oRange2
), no calculations
are necessary. But you already know easier ways to select the node and node contents; the real power
here is to be able to select only parts of nodes.
Recall the very first example mentioned in this section, selecting
llo
from
Hello
and
Wo
from
World
in
the HTML code
<p id=”p1”><b>Hello</b> World</p>
. Using
setStart()
and
setEnd()
, this is
quite easy to accomplish.
322
Chapter 10
13_579088 ch10.qxd 3/28/05 11:39 AM Page 322
Free JavaScript Editor
Ajax Editor
©
→