0

Suppose I have this HTML

<div id="someparent">
     Foo
     <span id="one">Selection starts anywhere inside here</span>
     <span id="two">Selection ends anywhere inside here</span>
     <span id="three">Some more text here</span>
     Bar
</div>

I want to return the span #one, and span #two nodes (so that I can wrap a further span round them*). If foo and bar are the start and end points of the selection, div #someparent would be returned (twice).

*How to do this would be helpful too even if with jQuery.

This is similar to this question which asks for the single parent of the whole selected text.

Community
  • 1
  • 1
Gazzer
  • 4,524
  • 10
  • 39
  • 49

2 Answers2

3

This code will return the parent nodes of the start and end of the selection:

var getSelectionParents=function(){
    var selection=document.getSelection();
    if(!selection.toString().length)
        return false;
    else
        return {
            start:selection.anchorNode.parentNode,
            end:selection.focusNode.parentNode
        };
}

document.addEventListener('mouseup',function(){
    console.log(getSelectionParents());
});

Here's a JSFiddle of the code in action: http://jsfiddle.net/jaredcrowe/wh1p3ncu/.

Jared
  • 718
  • 5
  • 11
  • This seems to work well. Is it cross-browser? Does it work in IE? (I'm not worried about supporting older version so mainly IE9 and later). – Gazzer Sep 14 '15 at 04:30
  • 1
    Yep, I've just tested that JSFiddle I provided in IE9 and IE11 and it appears to work in both. – Jared Sep 14 '15 at 05:17
  • There's a follow-up question here if you'd care to look :-) http://stackoverflow.com/questions/32557516/surround-2-sibling-elements-with-a-span – Gazzer Sep 14 '15 at 05:24
2

I think you can use the range to do that

$('button').click(function() {
  var selection = document.getSelection();

  var start = selection.getRangeAt(0);
  snippet.log('start: ' + start.startContainer.parentNode.id);
  snippet.log('end: ' + start.endContainer.parentNode.id);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<div id="someparent">
  Foo
  <span id="one">Selection starts anywhere inside here</span>
  <span id="two">Selection ends anywhere inside here</span>
  <span id="three">Some more text here[enter link description here][1]</span>
  Bar
</div>
<button>test</button>

Note: Not supported in IE

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531