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.
cletus May 10 '09 at 2:30 p.m. 2009-05-10 14:30
source share