Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent element of a selected text

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?

like image 507
MacMac Avatar asked Aug 27 '11 15:08

MacMac


People also ask

How do you find the parent element?

To get the parent node of an HTML element, you can use the parentNode property. This property returns the parent node of the specified element as a Node object. The parentNode property is read-only, which means you can not modify it.

What is the difference between parentNode and parentElement?

parentNode gives the parent, while . parentElement gives undefined.

What is parent element in HTML?

A parent is an element that is directly above and connected to an element in the document tree.


2 Answers

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;
}
like image 79
Tim Down Avatar answered Oct 10 '22 14:10

Tim Down


I'd suggest to use this

window.getSelection().anchorNode.parentElement

I have tested in safari osx 10.9

like image 25
chintan adatiya Avatar answered Oct 10 '22 14:10

chintan adatiya