views:

1304

answers:

5

Hi,

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?

+1  A: 

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
thnx but how do I get the entire paragraph even if they've only selected a couple of words?
Lily
+2  A: 
James Avery
+1 your solution does what Lily wants better than mine
Nadia Alramli
This doesn't work in IE.
Tim Down
+6  A: 

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() {
  var userSelection;
  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.

cletus
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
You're right, thanks and fixed.
cletus
I don't understand why this won't work in firefox :S
Lily
Fixed minor issue and improved browser compatibility.
cletus
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 :/
Lily
A: 

I have something useful... Unfortunately my script is written in italian language and is compatible only with Mozilla Firefox :(

...but I think it's very well constructed :)

You can find it here: http://sourceforge.net/projects/jsmatita.

P.S.: I'd like to translate it in english... if anybody is interested, contact me at: pincopalla00-at-gmail.com.

GoodBye :)

Pinco Palla
+1  A: 

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

TakeNotes