Main Page

DOM methods

The first step in the process is to get references to the text nodes containing
Hello
and
World
using the
regular DOM methods:
var oP1 = document.getElementById(“p1”);
var oHello = oP1.firstChild.firstChild;
var oWorld = oP1.lastChild;
The
Hello
text node is actually a grandchild of
<p/>
because it’s apparently
<b/>
, so you can use
oP1.firstChild
to get
<b/>
and
oP1.firstChild.firstChild
to get the text node. The
World
text
node is the second (and the last) child of
<p/>
, so you can use
oP1.lastChild
to retrieve it.
Next, create the range and set the appropriate offsets:
var oP1 = document.getElementById(“p1”);
var oHello = oP1.firstChild.firstChild;
var oWorld = oP1.lastChild;
var oRange = document.createRange();
oRange.setStart(oHello, 2);
oRange.setEnd(oWorld, 3);
For
setStart()
, the offset is 2, because the first
l
in
Hello
is in position
2
(starting from
H
in position
0). For
setEnd()
, the offset is 3, indicating the first character that
should not
be selected, which is
r
in
position 3. (There is actually a space in position 0. See Figure 10-3.)
Figure 10-3
Because both
oHello
and
oWorld
are text nodes, they become the
startContainer
and
endContainer
for the range so that the
startOffset
and
endOffset
accurately look at the text contained within each
node instead of looking for child nodes, which is what happens when an element is passed in. The
commonAncestorContainer
is the
<p/>
element, which is the first ancestor that contains both nodes.
Of course, just selecting sections of the document isn’t very useful unless you can interact with the
selection.
There is a bug in Mozilla’s implementation of the DOM Range (bug #135928) that
causes an error to occur when you try to use
setStart()
and
setEnd()
with the
same text node. This bug has been resolved and this fix is included in a future
Mozilla release.
<p id="pl"><b>Hello</b> World</p>
Range
01234
012345
323
Advanced DOM Techniques
13_579088 ch10.qxd 3/28/05 11:39 AM Page 323


JavaScript EditorFree JavaScript Editor     Ajax Editor


©