获取所选文本开头(和结尾)的父元素 [英] Get parent element of beginning (and end) of selected text

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

问题描述

假设我有这个HTML

Suppose I have this HTML

<div id="someparent">
     Foo
     <span id="one">Selection starts anywhere inside here</span>
     <span id="two">Selection ends anywhere inside here</span>
     <span id="three">Some more text here</span>
     Bar
</div>

我想返回跨度#one和跨度#two节点(以便我可以在它们周围进一步包裹跨度*).如果foo和bar是选择的起点和终点,则将返回div #someparent(两次).

I want to return the span #one, and span #two nodes (so that I can wrap a further span round them*). If foo and bar are the start and end points of the selection, div #someparent would be returned (twice).

*即使使用jQuery,如何执行此操作也将有所帮助.

*How to do this would be helpful too even if with jQuery.

这类似于此问题,要求整体的单亲选择的文字.

推荐答案

此代码将返回所选内容的开始和结束的父节点:

This code will return the parent nodes of the start and end of the selection:

var getSelectionParents=function(){
    var selection=document.getSelection();
    if(!selection.toString().length)
        return false;
    else
        return {
            start:selection.anchorNode.parentNode,
            end:selection.focusNode.parentNode
        };
}

document.addEventListener('mouseup',function(){
    console.log(getSelectionParents());
});

这是运行中的代码的JSFiddle: http://jsfiddle.net/jaredcrowe/wh1p3ncu/.

Here's a JSFiddle of the code in action: http://jsfiddle.net/jaredcrowe/wh1p3ncu/.

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

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