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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With