DOM Range Selections


The DOM Range API ( http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ ) 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();   myRange.setStartBefore(document.getElementById('p1'));   myRange.setEndAfter(document.getElementById('p2'));   alert(myRange);   /* Now highlight using Mozilla style selections */   mySelection = window.getSelection();   mySelection.addRange(myRange);  }  //-->> <</script>> 

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.




JavaScript 2.0
JavaScript: The Complete Reference, Second Edition
ISBN: 0072253576
EAN: 2147483647
Year: 2004
Pages: 209

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net