获取所选文本的父元素

是否可以在页面中获取所选文本的父元素? 例如:

Selection of this text should refer to the 'someparent' class. If this is selected, the parent should be this span

因为在获取所选文本时,它通常从窗口或文档中获取它(取决于浏览器),但是可以获取所选文本的父元素吗?

这是一个函数,它将为您提供包含所有主要浏览器中所有用户选择的最内层元素(除非选择了多个范围,仅在Firefox中支持。如果这很重要,我可以扩展示例来处理那个案子也是):

 function getSelectionParentElement() { var parentEl = null, sel; if (window.getSelection) { sel = window.getSelection(); if (sel.rangeCount) { parentEl = sel.getRangeAt(0).commonAncestorContainer; if (parentEl.nodeType != 1) { parentEl = parentEl.parentNode; } } } else if ( (sel = document.selection) && sel.type != "Control") { parentEl = sel.createRange().parentElement(); } return parentEl; } 

我建议用这个

 window.getSelection().anchorNode.parentElement 

我在safari osx 10.9中测试过