Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
118
rated 0 times [  124] [ 6]  / answers: 1 / hits: 28968  / 13 Years ago, sat, august 27, 2011, 12:00:00

Is it possible to get the parent element of a selected text in the page? For example:



<div class=someparent>

Selection of this text should refer to the 'someparent' class.

<span class=spanparent>If this is selected, the parent should be this span</span>

</div>


Because when getting the selected text, it normally gets it from the window or the document (depending on the browser) but is it that possible to get the parent element of the selected text?


More From » jquery

 Answers
12

Here's a function that will get you the innermost element that contains the whole of the user selection in all major browsers (except when multiple ranges are selected, which is only supported in Firefox. If this is important, I can expand the example to deal with that case too):



function getSelectionParentElement() {
var parentEl = null, sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
parentEl = sel.getRangeAt(0).commonAncestorContainer;
if (parentEl.nodeType != 1) {
parentEl = parentEl.parentNode;
}
}
} else if ( (sel = document.selection) && sel.type != Control) {
parentEl = sel.createRange().parentElement();
}
return parentEl;
}

[#90384] Thursday, August 25, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jadyngraysons

Total Points: 455
Total Questions: 109
Total Answers: 98

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
jadyngraysons questions
Thu, Apr 23, 20, 00:00, 4 Years ago
Sat, Jan 18, 20, 00:00, 4 Years ago
Tue, Dec 31, 19, 00:00, 5 Years ago
;