Question

I am trying to select the text some from text in this fiddle http://jsfiddle.net/vZ2fF/ but it does not seem to be working at all... what am I doing wrong???

<div contenteditable="true">
    <p id="ul1">
        <span id="span1">some element</span>
        <span>some element2</span>
    </p>
</div>

var selection1= window.getSelection();

var range1=document.createRange();
var ul= document.getElementById("ul1");

var idspan=document.getElementById("span1");

range1.setStart(idspan, 0);
range1.setEnd(idspan, 5);

selection1.addRange(range1);
Was it helpful?

Solution

jsBin demo

var Win = window, Doc = document;
var selection1 = Win.getSelection ? Win.getSelection() : Doc.selection.createRange();
var range = Doc.createRange();

function El(id){ return Doc.getElementById(id); }
var ul = El("ul1");
var idspan = El("span1").firstChild; // Note the Node element

range.setStart(idspan, 0);
range.setEnd(idspan, 4);

selection1.addRange(range);

http://www.quirksmode.org/dom/range_intro.html
https://developer.mozilla.org/en-US/docs/Web/API/range.setStart
https://developer.mozilla.org/en-US/docs/Web/API/range.setEnd
https://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#dom-range-setstart

OTHER TIPS

That is because, setEnd's second argument endOffset is the number of child nodes between the start of the endNode.

So, your idspan has only one child node that is textnode. So it will not work for range1.setEnd(idspan,5). For that, you need to have 5 child elements.

This will work: range1.setEnd(idspan,1), since the number of child nodes in idspan is just one (ie textnode).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top