Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select specific word with Javascript?

Tags:

javascript

I have the following code which selects the entire contents of an element:

function selectElement(element) {
    var sel = window.getSelection();
    sel.removeAllRanges();
    var range = document.createRange();
    range.setStart(element, 0);
    range.setEnd(element, 1);
    sel.addRange(range);
    console.log(range);
}

Which I call through:

selectElement(document.getElementById("input"));

If #input looks like this:

<div id="input">
Lorem Ipsum Dolor Sit
</div>

How can I select characters 0-7, so that the selection would be:

<div id="input">
[Lorem I]psum Dolor Sit
</div>

I figured setting the setStart and setEnd would work, but I can only set it from 0-1.

Can I select the text inside the node, instead of the node itself?

like image 245
Charlie Avatar asked Mar 01 '13 18:03

Charlie


2 Answers

You're passing the whole div node to setStart/setEnd, that's why you can only select between 0 and 1. You have to pass the div's firstChild instead, which is a text node. For example, to select "Ipsum":

range.setStart(element.firstChild, 7);
range.setEnd(element.firstChild, 12);

http://jsfiddle.net/JJ86n/

Note: dealing with ranges cross-browser has always been a mess. It's been a while since I don't deal with it, but last time I checked it seemed a good idea to let a library like rangy take care of the nasty details.

like image 152
bfavaretto Avatar answered Oct 31 '22 14:10

bfavaretto


You need to select it from the text node inside the element.

range.setStart(element.childNodes[0], 0);
range.setEnd(element.childNodes[0], 7);
like image 42
Tim Goodman Avatar answered Oct 31 '22 13:10

Tim Goodman