Getting the parent node for selected text with rangy library

别等时光非礼了梦想. 提交于 2019-12-04 21:54:35

问题


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>

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


回答1:


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


来源:https://stackoverflow.com/questions/10560155/getting-the-parent-node-for-selected-text-with-rangy-library

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!