Gazzer
Gazzer

Reputation: 4646

Get parent element of beginning (and end) of selected text

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.

Upvotes: 0

Views: 2167

Answers (2)

Jared
Jared

Reputation: 758

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/.

Upvotes: 3

Arun P Johny
Arun P Johny

Reputation: 388316

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

Upvotes: 2

Related Questions