04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 11: DOM Levels 2 and 3<br />

❑<br />

❑<br />

❑<br />

endContainer — The node within which the range ends (the parent of the last node in the<br />

selection).<br />

endOffset — The offset within the endContainer where the range ends (follows the same<br />

rules as startOffset ).<br />

commonAncestorContainer — The deepest node in the document that has both<br />

startContainer and endContainer as descendants.<br />

These properties are filled when the range is placed into a specific position in the document.<br />

Simple Selection in DOM Ranges<br />

The simplest way to select a part of the document using a range is to use either selectNode() or<br />

selectNodeContents() . These methods each accept one argument, a DOM node, and fill a range with<br />

information from that node. The selectNode() method selects the entire node, including its children,<br />

whereas selectNodeContents() selects only the node ’ s children. For example, consider the following<br />

HTML:<br />

< html ><br />

< body ><br />

< p id=”p1” > < b > Hello < /b > world! < /p ><br />

< /body ><br />

< /html ><br />

This code can be accessed using the following JavaScript:<br />

var range1 = document.createRange();<br />

var range2 = document.createRange();<br />

var p1 = document.getElementById(“p1”);<br />

range1.selectNode(p1);<br />

range2.selectNodeContents(p1);<br />

The two ranges in this example contain different sections of the document: range1 contains the < p/ ><br />

element and all its children, whereas range2 contains the < b/ > element, the text node “ Hello ” , and the<br />

text node “ world! ” (see Figure 11 - 6 ).<br />

range1<br />

p id"p1"bHello/b world!/p<br />

Figure 11-6<br />

range2<br />

When selectNode() is called, startContainer , endContainer , and commonAncestorContainer are<br />

all equal to the parent node of the node that was passed in; in this example, these would all be equal to<br />

document.body . The startOffset property is equal to the index of the given node within the parent ’ s<br />

childNodes collection (which is 1 in this example — remember DOM - compliant browsers count white<br />

space as text nodes), whereas endOffset is equal to the startOffset plus one (because only one node<br />

is selected).<br />

350

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!