select-range-in-contenteditable-div

Test for Javascript Range manipulation

by Abeee Doe

HTML

<div id="main" contenteditable="true" 
     style="border:solid 1px black; width:300px; height:300px">
   <div id='one'>Hello world!</div>
   <div id='two'>
      <br>
   </div>
   <div id='three'>This is a paragraph</div>
</div>

JavaScript

var mainDiv = document.getElementById("main");
var startNode = mainDiv.firstChild.firstChild;
var endNode = mainDiv.childNodes[2].firstChild;

var range = document.createRange();
range.setStart(startNode, 6); // 6 is the offset of "world" within "Hello world"
range.setEnd(endNode, 7); // 7 is the length of "this is"
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);