0

Setting focus is simple enough: node.focus(). I've had limited success looking at other answers. I can set the cursor at either the beginning or end, or I can select the whole contents with this code in chrome:

// if start==0 means the beginning, start===1 means the end
function setSelection(node, start, length) {
    var range = document.createRange();
    range.setStart(node, start);
    range.setEnd(node, length);
    //range.collapse(true);

    var selection = getSelection()
    selection.removeAllRanges();
    selection.addRange(range);
}

So the question is: how can I set the cursor more granularly, say at character 2. Also, how can I set the selection, for example from character 2 to character 5?

MDN tells me that Range.setStart has different behavior for Text, Comment, or CDATASection nodes than other nodes. If I could get setStart to treat a div like a Text node, I think my problem might be solved.

Anyone have any ideas?

B T
  • 57,525
  • 34
  • 189
  • 207
  • 1
    http://stackoverflow.com/a/16100733/96100 – Tim Down Jun 17 '14 at 08:54
  • I have seen that answer already. It is not the same question I'm asking. In fact, I explicitly say in my question this is about non-Text nodes. – B T Jun 17 '14 at 21:25
  • In which case you need to read that answer again. It does exactly what you want, with a few caveats. – Tim Down Jun 18 '14 at 08:17
  • Ah, in first testing it seemed not to work because of the hidden whitespace caveat. Thanks. – B T Jun 19 '14 at 20:01

0 Answers0