1

I found a really cool bit of code in this post to capture all the text a user highlights within a div. However, in my case I would like to actually store the element ids of all the elements selected in a div. I can do this by manipulating the output of the following example (based on the earlier mentioned post), but I was hoping there's a more elegant way to directly retrieve the elements selected?

function getSelectionHtml() {
    var html = "";
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    return html;
}
$("#div_1").on("mouseup",function(){
  console.dir(getSelectionHtml());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div_1">
  <span id="span_1">Span 1 text</span>
  <span id="span_2">Span 2 text</span>
  <span id="span_3">Span 3 text</span>
  <span id="span_4">Span 4 text</span>  
</div>

1 Answers1

0

I realised after posting this question that I can adapt the code I was using to get my answer (as the original code I was using loops through selected children):

function getSelectionChildrenHtml() {
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {                container.appendChild(sel.getRangeAt(i).cloneContents());
                var children = sel.getRangeAt(i).cloneContents().children;
            }            
        }
    } 
    return children;
}
$("#div_1").on("mouseup",function(){
  console.dir(getSelectionChildrenHtml());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div_1">
  <span id="span_1">Span 1 text</span>
  <span id="span_2">Span 2 text</span>
  <span id="span_3">Span 3 text</span>
  <span id="span_4">Span 4 text</span>  
</div>