Choose a specific word using Javascript?

I have the following code that 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); } 

What I call:

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

If #input looks like this:

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

How to select characters 0-7 so that the selection is:

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

I decided to install setStart and setEnd , but I can only install it from 0-1 .

Is it possible to select the text inside the node, and not the node itself?

+4
source share
3 answers

You pass the entire div node to setStart / setEnd , so you can only choose between 0 and 1. You need to pass the div firstChild , and this is the text node. For example, to select "Ipsum":

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

http://jsfiddle.net/JJ86n/

Note. Working with cross-browser ranges has always been a mess. It has been a while since I did not do this, but the last time I checked, it was nice to let the library, for example rangy, take care of the unpleasant details.

+2
source

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

 range.setStart(element.childNodes[0], 0); range.setStart(element.childNodes[0], 7); 
+1
source

You are dealing with the whole element, which is an object that has different objects as properties. To deal with Strings, you first need to get the String (text) subscript element. You can do this by getting the child of a node from an array of child nodes of the elements. Attempting to use a JavaScript String property or method, such as length or substr directly in the Selection object, will result in an error if it does not have this property or method and may return unexpected results if this happens.

0
source

All Articles