简体   繁体   English

使用rangy库获取所选文本的父节点

[英]Getting the parent node for selected text with rangy library

I'm using the rangy library and can select text in a content editable as follows: 我正在使用rangy库,可以选择内容可编辑的文本,如下所示:

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>

how can I include the strong node or H1 element also? 如何包含强节点或H1元素?

sel.anchorNode.parentNode will get you the parent node of the node containing only one end of the selection. sel.anchorNode.parentNode将为您提供仅包含选择的一端的节点的父节点。 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): 要获得整个选择的最内层包含元素,最简单的方法是从选择中获取一个Range并查看其commonAncestorContainer属性(可能是文本节点,在这种情况下,您需要获取其父级):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM