Main Page

Simple selection in DOM ranges

If you plan to use DOM ranges, it is always best to make this check first and wrap your code in an
if
statement:
if (supportsDOMRange) {
var oRange = document.createRange();
//range code here
}
Simple selection in DOM ranges
The simplest way to select a part of the document using a range is to use either
selectNode()
or
selectNodeContents()
. These methods each accept one argument, a DOM node, and fill a range with
information from that node.
The
selectNode()
method selects the entire node, including its children, whereas
selectNodeContents()
selects all of the node’s children. For example, consider the following:
<p id=”p1”><b>Hello</b> World</p>
This code can be accessed using the following JavaScript:
var oRange1 = document.createRange();
var oRange2 = document.createRange();
var oP1 = document.getElementById(“p1”);
oRange1.selectNode(oP1);
oRange2.selectNodeContents(oP1);
The two ranges in this example contain different sections of the document: oRange1 contains the
<p>
element and all its children, whereas oRange2 contains the
<b/>
element and the text node
World
(see
Figure 10-1).
Figure 10-1
Whenever you create a range, a number of properties are assigned to it:
?
startContainer
— The node within which the range starts (the parent of the first node in the
selection)
?
startOffset
— The offset within the
startContainer
where the range starts. If
startContainer
is a text node, comment node, or CData node, the
startOffset
is the num-
ber of characters skipped before the range starts; otherwise, the offset is the index of the first
child node in the range.
<p id="pl"><b>Hello</b> World</p>
<p id="pl"><b>Hello</b> World</p>
oRange1.selectNode(oP1)
oRange2.selectNodeContents(oP1)
318
Chapter 10
13_579088 ch10.qxd 3/28/05 11:39 AM Page 318


JavaScript EditorFree JavaScript Editor     Ajax Editor


©