获取所选文本的父元素

问题描述:

是否可以在页面中获取所选文本的父元素?例如:

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?

这是一个能让你获得的功能最内层的元素,包含所有主流浏览器中的所有用户选择(除非选择了多个范围,只有Firefox支持。如果这很重要,我可以扩展示例来处理这种情况):

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