Set selection by range in Javascript
Asked Answered
G

2

29

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

Gormand answered 16/7, 2013 at 11:14 Comment(4)
@AndyG I am using it in my IOS app.Remaining function are working okay but the issue is only with setStart and setEnd both are not workingGormand
@AndyG: Wrong way round. document.createRange() is the standard, supported by everything except IE <= 8.Puzzle
Thank you @TimDown. I was looking at selection.createRange.Argilliferous
Check this link: javascript.info/selection-rangeBarnette
P
23

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;
Puzzle answered 16/7, 2013 at 13:59 Comment(2)
Great It working in the case if I have only one text line in the "content". What about if I have applied bold or font tag on the string.Gormand
@ShinningRiver: Then you'll need a more complicated solution, like https://mcmap.net/q/83217/-persisting-the-changes-of-range-objects-after-selection-in-htmlPuzzle
C
19

Here's a good solution if you're trying to select a jquery result set

var $newSelection = $('.someElements');
var selection = window.getSelection();
var range = document.createRange();
range.setStartBefore($newSelection.first()[0]);
range.setEndAfter($newSelection.last()[0]);
selection.removeAllRanges();
selection.addRange(range);
Confirmed answered 4/5, 2015 at 19:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.