I have a span inside the contenteditable div and I need to figure out if the cursor is in the last position on the span tag. I looked in the Selection and Range solutions but couldn't figure out a straight forward way to achieve that.
<html>
<script>
var selection = window.getSelection();
var range = selection.getRangeAt(0);
//this is what I am trying to achive
var selection_target = range.selectNodeContents(document.getElementById('target'));
var length = selection_target.toString().length;
</script>
<body>
<div id='target' contenteditable='true'>
<span>some text(figure cursor position here)</span>
</div>
</body>
</html>
For the case in the question where the span only has one child that is a text node, you can check whether the caret is at the end of it as follows:
Demo: http://jsfiddle.net/Wm5Hz/
Code:
var span = document.getElementById("target").getElementsByTagName("span")[0];
var spanTextNode = span.lastChild;
var sel = window.getSelection();
var isCaretAtEndOfSpan = (sel.isCollapsed
&& sel.focusNode == spanTextNode
&& sel.focusOffset == spanTextNode.data.length);
Things are slightly more complicated in the general case: the same visual position can be represented in different ways (e.g. after the last character in the text node, after the text node itself, after the end of the span), plus if the span could contain elements then you'd need to find the last text node within the span and compare the selection against it. Also, none of this works in IE < 9, which has a completely different API.