Sunday, August 05, 2007

DOM Range Selections

DOM Range Selections
The DOM Range API ( introduced in DOM Level 2 is another convenience extension that allows you to select a range of content in a document programmatically. To create a range, use document.CreateRange(), which will return a Range object.
var myRange = document.createRange();

Once you have a Range object, you can set what it contains using a variety of methods. Given our example range, we might use myRange.setStart(), myRange.setEnd(), myRange.setStartBefore(), myRange.setStartAfter(), myRange.setEndBefore(), and myRange.setEndAfter() to set the start and end points of the range. Each of these methods takes a Node primarily, though setStart() and setEnd() take a numeric value indicating an offset value. You may also just as easily select a particular node using myRange.selectNode() or its contents using myRange.selectNodeContents(). A simple example here selects two paragraphs as a range.

<p id="p1">This is sample <em>text</em> go ahead and create a <i>selection</i>
over a portion of this paragraph.</p>
<p id="p2">Another paragraph</p>
<p id="p3">Yet another paragraph.<br/></p>
<p id="p4">Yet another paragraph again.</p>
<p id="m">

[IE]Once you have a range, you can perform a variety of methods upon it, including extractContents(), cloneContents(), and deleteContents(), and even add contents using insertNode(). While the Range API is quite interesting, it is at the time of this edition’s writing only partially implemented in Mozilla. Internet Explorer uses a completely different proprietary method for ranges and selections. </p>

<script type="text/javascript">
var myRange1;
var myRange2;
var myRange3;
var myDiv;
var p1 = document.getElementById('p1');
if (document.createRange) {
myRange1 = document.createRange();
myRange2 = document.createRange();
myRange3 = document.createRange();
myDiv = myRange3.createContextualFragment('<div id="d1">test createContextualFragment of Mozilla</div>');
/* Now highlight using Mozilla style selections */
mySelection = window.getSelection();

No comments :