使用rangy库获取所选文本的父节点 [英] Getting the parent node for selected text with rangy library

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

问题描述

我正在使用 rangy 库,可以选择内容中可编辑的文字,如下所示:

I'm using the rangy library and can select text in a content editable as follows:

var sel = rangy.getSelection();
alert(sel);

我无法弄清楚如何获取所选文本父节点/元素。例如,如果我选择的文字是

I can't figure out how to get the selected text parent node/element. For example, if I'm selecting text that is

<strong>My Text</strong> 
or
<h1>My Title</h1>

我如何包含强节点或H1元素?

how can I include the strong node or H1 element also?

推荐答案

sel.anchorNode.parentNode 将获得仅包含选择的一端的节点的父节点。要获得整个选择的最内层包含元素,最简单的方法是从选择中获取一个Range并查看其 commonAncestorContainer 属性(可以是文本节点,在哪种情况下你需要得到它的父母):

sel.anchorNode.parentNode will get you the parent node of the node containing only one end of the selection. To get the innermost containing element for the whole selection, the easiest thing is to get a Range from the selection and look at its commonAncestorContainer property (which may be a text node, in which case you need to get its parent):

var sel = rangy.getSelection();
if (sel.rangeCount > 0) {
    var range = sel.getRangeAt(0);
    var parentElement = range.commonAncestorContainer;
    if (parentElement.nodeType == 3) {
        parentElement = parentElement.parentNode;
    }
}

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

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