Set selection by range in Javascript

Shinning River picture Shinning River · Jul 16, 2013 · Viewed 35.7k times · Source

I want to select text by sending location/anchorOffset and length/offset using Javascript Here is my code

  var node = document.getElementById("content");
   var range = document.createRange();
   range.setStart(node, 0);
   range.setEnd(node, 4); // here 0 and 4 is my location and length for the selection
       // if my string is "This is test string" in my case its must select "This" 
   var selection = window.getSelection();
   selection.removeAllRanges();
    selection.addRange(range);

But the issue is with range.setStart and range.setEnd its not working as I expect

Answer

Tim Down picture Tim Down · Jul 16, 2013

The setStart() and setEnd() methods of DOM Range are well specified, so you could find the answer by reading the spec or MDN.

To summarise, if you want to specify a range boundary in terms of character offsets, you need to deal with a text node rather than an element. If your element contains a single text node, changing the first line of your code to the following will work:

var node = document.getElementById("content").firstChild;