Skip to content

Instantly share code, notes, and snippets.

@endpnt
Created April 19, 2011 00:32
Show Gist options
  • Select an option

  • Save endpnt/926585 to your computer and use it in GitHub Desktop.

Select an option

Save endpnt/926585 to your computer and use it in GitHub Desktop.
find actual text start and end position of a selected text, even with childNodes present.
var offset = 0;
var selection = window.getSelection();
var range = selection.getRangeAt(0);
var start = range.startOffset;
var end = range.endOffset;
if ( selection.baseNode.parentNode.hasChildNodes() ) {
for ( var i = 0 ; selection.baseNode.parentNode.childNodes.length > i ; i++ ) {
var cnode = selection.baseNode.parentNode.childNodes[i];
if (cnode.nodeType == document.TEXT_NODE) {
if ( (offset + cnode.length) > start) {
break;
}
offset = offset + cnode.length;
}
if (cnode.nodeType == document.ELEMENT_NODE) {
if ( (offset + cnode.textContent.length) > start) {
break;
}
offset = offset + cnode.textContent.length;
}
}
}
start = start + offset;
end = end + offset;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment