获取所选文本的父元素 [英] Get parent element of a selected text

查看:148
本文介绍了获取所选文本的父元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于获取所选文本的父元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆