Javascript to get a paragraph of selected text on a web page

After selecting the text, I would like to get the paragraph in which the selected text is located.

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

Any pointers please?

+15
javascript document window paragraph webpage
May 10 '09 at 14:04
source share
5 answers

This is quite difficult to do because you need to consider six cases:

  • The selection is not in the paragraph (easy);
  • The entire selection is within the same paragraph (easy);
  • The entire selection crosses one or more paragraphs (more complex);
  • The selection begins or ends with an element not contained in the paragraph (more complex);
  • Items covered at different levels, for example, one is in the list item, and the other two are siblings from the list (even harder); and
  • Some combination of the above.

So, firstly, you need to decide how completely you want the solution to be. I will tell only the simplest cases (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 are behind the tags also replace textContent with innerHTML.

Edit: Added a better version, including better browser compatibility.

+16
May 10 '09 at 2:30 p.m.
source share

I found this useful example .

It seems that some browsers support window.getSelection (), while others support document.getSelection (). This example handles all of these cases.

+4
May 10 '09 at
source share

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

and you can get the text of this node.

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

Make sure you look at window.getSelection () as document.getSelection depreciates in firefox.

+4
May 10 '09 at 2:14
source share

A new project is born from jsmatita: http://takenotes.sourceforge.net/ (this is in Italian)

+1
Mar 28
source share
 $.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> 

Here you can find the fiddle https://jsfiddle.net/q9nkc0fd/6/

+1
Mar 31 '16 at 21:50
source share



All Articles