最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting the parent node for selected text with rangy library - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited May 12, 2012 at 10:36 skaffman 404k96 gold badges824 silver badges775 bronze badges asked May 12, 2012 at 0:43 FrankFrank 7141 gold badge9 silver badges21 bronze badges 1
  • 1 Messing around some more I see that I can use: sel.anchorNode.parentNode.nodeName – Frank Commented May 12, 2012 at 1:10
Add a ment  | 

1 Answer 1

Reset to default 8

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 monAncestorContainer 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.monAncestorContainer;
    if (parentElement.nodeType == 3) {
        parentElement = parentElement.parentNode;
    }
}
发布评论

评论列表(0)

  1. 暂无评论