.contains() return false in Internet Explorer

This code return false in Internet Explorer. Any alternative?

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

I want to check whether the div element contains the selected range:

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

I want to check whether the div element contains the selected range:

Current behavior in internet explorer: Current behavior in internet explorer:

1 answer

  • answered 2018-04-17 06:09 Ramesh Rajendran

    You don't need child Node.

    Because the DOM contains check the full DOM not the Node Child. Please try this below function instead of yours. And it is working!

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

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