This code在Internet Explorer中返回false。还有其他选择吗?

<!DOCTYPE html>
<html>

<head>
  <style>
    #myDIV {
      border: 1px solid black;
    }
  </style>
</head>

<body>

  <div id="myDIV">
    <p>I am a p element inside div, and I have a <span id="mySPAN">span</span> element inside of me.</p>
  </div>
  <p>I am a p element inside div, and I have a <span id="mySPAN">span</span> element inside</p>


  <button onclick="myFunction()">Try it</button>

  <p id="demo"></p>

  <script>
    function myFunction() {
      var span = document.getElementById("mySPAN");
      var text = span.childNodes[0];
      var div = document.getElementById("myDIV").contains(text);
      document.getElementById("demo").innerHTML = div;
    }
  </script>

</body>

</html>


我想检查div元素是否包含所选范围:
function getRange(root): Range {
    const sel = window.getSelection();
    const range = sel.getRangeAt(0);
    if (range && range.commonAncestorContainer !== root && root.contains(range.commonAncestorContainer)) {
        return range.cloneRange();
    }
    return null;
}

我想检查div元素是否包含所选范围:

Internet Explorer中的当前行为:
javascript - .contains()在Internet Explorer中返回false-LMLPHP

最佳答案

您不需要子节点。

因为DOM包含检查完整的DOM,而不是Node Child。请尝试使用以下功能代替您的功能。它正在工作!

<script>
function myFunction() {
    var span = document.getElementById("mySPAN");
    var div = document.getElementById("myDIV").contains(span);
    document.getElementById("demo").innerHTML = div;
}
</script>

演示:https://www.w3schools.com/code/tryit.asp?filename=FQFMFOKPLHO3

09-15 12:12