是否可以在页面中获取所选文本的父元素?例如:
<div class="someparent">
Selection of this text should refer to the 'someparent' class.
<span class="spanparent">If this is selected, the parent should be this span</span>
</div>
因为在获取所选文本时,它通常从窗口或文档中获取它(取决于浏览器),但是可以获取所选文本的父元素吗?
答案 0 :(得分:37)
这是一个函数,它将为您提供包含所有主要浏览器中所有用户选择的最内层元素(除非选择了多个范围,仅在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;
}
答案 1 :(得分:8)
我建议使用此
window.getSelection().anchorNode.parentElement
我在safari osx 10.9中进行了测试
答案 2 :(得分:1)
@Tim Down's的答案很好,可以添加更多有用的代码来达到特定父级的html内容:
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();
}
while(true){
// I want to reach upper <span> parent
if(parentEl.nodeName == "SPAN"){
console.log(parentEl);
break;
}
else{
parentEl = parentEl.parentNode;
}
}
}
例如:
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();
}
while(true){
// I want to reach upper <span> parent
if(parentEl.nodeName == "P"){
document.getElementById("printable").innerText = parentEl.innerHTML;
break;
}
else{
parentEl = parentEl.parentNode;
}
}
}
<head>
<style type="text/css">
@media print
{
#non-printable { display: none; }
#printable { display: block; }
}
</style>
</head>
<p>The <strong>coronavirus</strong> COVID-19 is affecting <strong>210 <i>countries</i> and territories</strong> around the world and 2 international conveyances.</p>
<div id="printable">Output: </div>
<button onclick="getSelectionParentElement()">Select 'countries' and click me.</button>