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?