javascript 获取所选文本的父元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7215479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:20:06  来源:igfitidea点击:

Get parent element of a selected text

javascriptjquerytext

提问by MacMac

Is it possible to get the parent element of a selected text in the page? For example:

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

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

Because when getting the selected text, it normally gets it from the window or the document (depending on the browser) but is it that possible to get the parent element of the selected text?

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

回答by Tim Down

Here's a function that will get you the innermost element that contains the whole of the user selection in all major browsers (except when multiple ranges are selected, which is only supported in Firefox. If this is important, I can expand the example to deal with that case too):

这是一个函数,它可以让你得到所有主要浏览器中包含整个用户选择的最内层元素(除非选择了多个范围,这仅在 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;
}

回答by chintan adatiya

I'd suggest to use this

我建议使用这个

window.getSelection().anchorNode.parentElement

I have tested in safari osx 10.9

我已经在 safari osx 10.9 中进行了测试

回答by ATES

@Tim Down'sanswer works good, to add more useful code for reaching the specific parent's html content:

@Tim Down 的回答很有效,可以添加更多有用的代码来访问特定父级的 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;
      }
  }
}

For example:

例如:

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