Javascript get enclosing element of selected text


Web Programming


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;
}

Example:

Get the closest enclosing <div> of the selected text with class ‘entry-content’:


$(getSelectionParentElement()).closest('div.entry-content')

References:

1. http://stackoverflow.com/questions/7215479/get-parent-element-of-a-selected-text
2. http://api.jquery.com/closest/

View original post