Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set selection by range in Javascript

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

like image 743
Shinning River Avatar asked Jul 16 '13 11:07

Shinning River


People also ask

What is selection range JavaScript?

The basic concept of selection is Range, that is essentially a pair of “boundary points”: range start and range end. A Range object is created without parameters: let range = new Range(); Then we can set the selection boundaries using range.

How do you use setSelectionRange?

setSelectionRange() method sets the start and end positions of the current text selection in an <input> or <textarea> element. Optionally, in newer browser versions, you can specify the direction in which selection should be considered to have occurred.

What is window getSelection?

getSelection() The Window. getSelection() method returns a Selection object representing the range of text selected by the user or the current position of the caret.


2 Answers

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; 
like image 61
Tim Down Avatar answered Sep 23 '22 01:09

Tim Down


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); 
like image 25
Charlie Avatar answered Sep 24 '22 01:09

Charlie