Team LiB
Previous Section Next Section

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.<</p>>

<<script type="text/javascript">>

var myRange;

if (document.createRange)
  myRange = document.createRange();

  /* Now highlight using Mozilla style selections */
  mySelection = window.getSelection();

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.

Team LiB
Previous Section Next Section