Open In App

Web API Selection collapse() Method

Last Updated : 16 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The collapse() method is used to collapse the current selection to a single position. The collapse() method does not modify the document. 

Syntax:

collapse(node)
collapse(node, offset)

Parameters: This method accepts two parameters.

  • node: The caret location within the node. You can also pass a null in this parameter. If null specifies the method will behave like this removeAllRanges() method i.e all ranges will be removed from the selection.
  • offset: This is an optional parameter. The default value is 0.

Return Value: This method does not return any specific value.

Example 1: In this example, we will select the statement by clicking the button, and collapse the method by using the collapse() method.

HTML




<!DOCTYPE html>
<html>
<head>
    <title>Web API Selection collapse() Method</title>
</head>
  
<body>
    <h1 style="color:green">
          GeeksforGeeks
      </h1>
    <p>
        I insist that you try selecting the strong words.
    </p>
    <button onclick="range();">Select All Words</button>
    <button onclick="work();">Collapse method</button>
    <script>
  
        function range() {
            const selection = window.getSelection();
            const strongs = document.getElementsByTagName('p');
  
            if (selection.rangeCount > 0) {
                selection.removeAllRanges();
            }
            for (const node of strongs) {
                const range = document.createRange();
                range.selectNode(node);
                selection.addRange(range);
            }
        }
        function work() {
            const body = document.querySelector("body");
            window.getSelection().collapse(body, 0);
  
        }
    </script>
</body>
    
</html>


Output:

collapse() Method

collapse() Method

 

Example 2: In this example, we will manually select the statement, and collapse the method by using the collapse() method.

HTML




<!DOCTYPE html>
<html>
<head>
    <title>Collapse Method Example </title>
</head>
  
<body>
    <h1 style="color:green">
          GeeksforGeeks
      </h1>
    <h2>Select Some text and click the button</h2>
    <button> Collapse Me </button>
    <script>
        var button = document.querySelector('button');
        button.addEventListener("click", () => {
            window.getSelection().collapse(null, 0);
        });
    </script>
</body>
    
</html>


Output:

 

 Reference: https://developer.mozilla.org/en-US/docs/Web/API/Selection/collapse#examples



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads