Created
April 19, 2011 00:32
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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