Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript to get paragraph of selected text in web page

Tags:

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?

like image 815
Lilz Avatar asked May 10 '09 14:05

Lilz


People also ask

How do you select a paragraph in HTML?

The most basic of the selectors is an element selector. For example, paragraphs in an HTML document are represented by the p element and wrapped in <p></p> tags. To select all paragraphs in a document we would use the following selector. To select all level 1 headings we would use the h1 selector.

What is window getSelection?

getSelection() The Window. getSelection() method returns a Selection object representing the range of text selected by the user or the current position of the caret.


2 Answers

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.

like image 158
cletus Avatar answered Oct 15 '22 15:10

cletus


I found this useful example.

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

like image 27
Nadia Alramli Avatar answered Oct 15 '22 16:10

Nadia Alramli