Select specific word with Javascript?

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.


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

range.setStart(element.childNodes[0], 0);
range.setEnd(element.childNodes[0], 7);

Tags:

Javascript