Open In App

Web API Selection.containsNode() Method

Last Updated : 14 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The Selection API gives developers the ability to recognize the screen regions that the user has now selected and to use code to initiate user selections.

The containsNode() method is used to determine whether a specified node is part of the selection or not.

Syntax:

containsNode(node, partialContainment)

Parameters:

  • node: The node in the selection that is being sought after.
  • partialContainment: The method returns “true” when the selection includes a portion of the node. When the argument is “false”, the method only returns “true” if the complete node is included in the selection. If nothing is entered, “false” is used by default.

Returns: None

Example 1: This example will check if the selection contains the span with the id ‘special’.

HTML




<!DOCTYPE html>
<html>
  
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    <h3> Web API selection containsNode method</h3>
    <p>Hi <span id="special">please</span> select this</p>
    <button type="button" onclick="clickHandler()">
        Click Here!!!
    </button>
    <script>
        let node = document.getElementById('special')
  
        function clickHandler() {
            let selection = window.getSelection();
            let res = selection.containsNode(node);
            alert(res);
        }
    </script>
</body>
  
</html>


Output:

 

Example 2: In this example, we will check for partial selection for the span with id ‘special’.

HTML




<!DOCTYPE html>
<html>
  
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    <h3> Web API selection containsNode method</h3>
    <p>This example will explain the partial 
       selection of a node.
      <span id="special">THIS IS THE PART.</span
      The containsNode method also allows for 
      checking partial containment.
    </p>
    <button type="button" onclick="clickHandler()">
        Click Here!!!
    </button>
    <script>
        let node = document.getElementById('special')
  
        function clickHandler() {
            let selection = window.getSelection();
            let res = selection.containsNode(node, true);
            alert(res);
        }
    </script>
</body>
  
</html>


Output:

 

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Selection/containsNode



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads