获取所选文本的开头(和结尾)的父元素

假设我有这个HTML

Foo Selection starts anywhere inside here Selection ends anywhere inside here Some more text here Bar

我想返回跨度#one ,并且跨越#two节点(这样我可以围绕它们换一个跨度*)。 如果foo和bar是选择的起点和终点,则会返回div #someparent (两次)。

*即使使用jQuery,如何做到这一点也会有所帮助。

这类似于这个问题,要求整个选定文本的单亲 。

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

 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/ 。

我想你可以使用这个范围来做到这一点

 $('button').click(function() { var selection = document.getSelection(); var start = selection.getRangeAt(0); snippet.log('start: ' + start.startContainer.parentNode.id); snippet.log('end: ' + start.endContainer.parentNode.id); }) 
    
Foo Selection starts anywhere inside here Selection ends anywhere inside here Some more text here[enter link description here][1] Bar