23

After highlighting text, I would like to obtain the paragraph in which the selected text resides.

var select = window._content.document.getSelection();

Any pointers please?

Lilz
  • 4,013
  • 13
  • 61
  • 95

7 Answers7

24

This is actually rather hard to do because you have to consider six cases:

  1. The selection is not within a paragraph (easy);
  2. The entire selection is within one paragraph (easy);
  3. The entire selection crosses one or more sibling paragraphs (harder);
  4. The selection starts or ends in an element not within a paragraph (harder);
  5. The paragraphs spanned are at different levels eg one is within a list item while two others are siblings of the list (even harder); and
  6. Some combination of the above.

So firstly you have to decide how complete you want the solution to be. I'll only cover the simplest cases of (1) and (2).

function getSelectedParagraphText() {
  if (window.getSelection) {
      selection = window.getSelection();
  } else if (document.selection) {
      selection = document.selection.createRange();
  }
  var parent = selection.anchorNode;
  while (parent != null && parent.localName != "P") {
    parent = parent.parentNode;
  }
  if (parent == null) {
    return "";
  } else {
    return parent.innerText || parent.textContent;
  }
}

Note: If you're after tags too replace textContent with innerHTML.

Edit: Better version put in, including better browser compatibility.

pegasuspect
  • 991
  • 4
  • 15
cletus
  • 616,129
  • 168
  • 910
  • 942
  • anchor.parentNode won't work in your example, you would need to do anchor.anchorNode.parentNode. (this is in firefox, I didn't test in IE or others). – James Avery May 10 '09 at 14:41
  • Fixed minor issue and improved browser compatibility. – cletus May 10 '09 at 17:43
  • I have no idea how to thank you. I still have a minor error...and I'm quite embarrassed to ask you yet another question. Unfortunately its returning a null and I cannot understand why :/ – Lilz May 10 '09 at 19:53
  • Please note that the document.selection.createRange() does not have a property .anchorNode, so this will not work in IE8 or less. I'd love to see a working example for such browsers, so I can vote this up again. – arxpoetica Jul 26 '12 at 14:57
6

I found this useful example.

It seems that some browsers support window.getSelection() while others support document.getSelection(). The example handle all these cases.

Nadia Alramli
  • 111,714
  • 37
  • 173
  • 152
  • thnx but how do I get the entire paragraph even if they've only selected a couple of words? – Lilz May 10 '09 at 14:10
4

select.anchorNode.parentNode will return the parent node, in your case the

tag and you can then get the text of that node.

var x = window.getSelection() 
var z = x.anchorNode.parentNode
alert(z.innerHTML)

Make sure you look at window.getSelection() as well since document.getSelection is depreciated in firefox.

James Avery
  • 3,062
  • 1
  • 20
  • 26
3
$.event.props.push('onTextSelect');
$(document).click(function(){
    var str=window.getSelection().anchorNode.data;
    var str=str.substring(window.getSelection().anchorOffset,window.getSelection().focusOffset);
    if(str)
        $(window.getSelection().focusNode.parentNode).trigger({type:'onTextSelect',text:str});
});

$('p').on('onTextSelect',function(e){
    console.log($(this).attr('class'))
    $('p:last').text(e.text);
});

html

<div><p class="p">some text</p></div>
<p></p>

You can find the fiddle here https://jsfiddle.net/q9nkc0fd/6/

1

A new project is born from jsmatita: http://takenotes.sourceforge.net/ (it's in italian language)

TakeNotes
  • 11
  • 1
0

I reproduced code from answer above from @Thiago Souza and created a snippet for that purpose for those who can provide a correct answer.

function getSelectedParagraph(){
  const selection = window.getSelection();
  let parent = selection.anchorNode;

  while (parent != null && parent.nodeName != "P") {
    parent = parent.parentNode;
  };

  console.log(parent);

  return parent;
};

window.onload = getSelectedParagraph();
<div class='paragraph-container'>
  <p id='paragraph-01'>
    Paragraph 1: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>
  <p id='paragraph-02'>
    Paragraph 2: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>
  <p id='paragraph-03'>
    Paragraph 3: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>
</div>
Jürgen Fink
  • 3,162
  • 2
  • 23
  • 25
-1
function getSelectedParagraph(){
      
      const selection = window.getSelection();
    
      let parent = selection.anchorNode;
                    
      while (parent != null && parent.nodeName != "P") {
          parent = parent.parentNode;
      }
                  
      return parent;
      
    }