I am trying to get character offsets for the beginning and end of the selection inside the article. However, I would like some elements to be ignored from this process.
In my application, the server works with HTML before JS dynamically injects several elements, and it is very important that the number of characters in the text remains consistent between the server and the client.
I was hoping this would be as simple as window.getSelection() along with user-select: none; . Unfortunately, although the text does not appear to be selected, it is still included in the selection range.
I wrote a short example below. I had the chance to write removeFromSelection as a workaround without much success. Maybe I need to remove ranges that overlap .unselectable and manually fill in the blanks with new range objects. I feel that it should be easier than I do. How am I supposed to do this?
function findAncestorOffset(container, node, offset) { if (node == container) return offset; var parent = node.parentNode; var syblings = parent.childNodes; for (var i = 0, len = syblings.length; i < len; i++) { if (syblings[i] == node) break; offset += $(syblings[i]).text().length; } return findAncestorOffset(container, parent, offset); } function removeFromSelection(selector, selection) { $(selector).each(function(i, node){ var range = document.createRange(); range.selectNodeContents(node); selection.removeAllRanges(range); }); } var onSelect = function(){ var sel = window.getSelection();
.unselectable { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } pre, .article { border: solid 1px black; padding: 12px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1>Select This</h1> <div class="article"> <p> This can be selected. </p> <p class="unselectable"> This can't. </p> <p> And this can again. </p> </div> <h1>Output</h1> <div> From: <span id="from"></span>, To: <span id="to"></span> </div> <pre id="out"> </pre>
source share