Open In App

HTML DOM Range collapse() Method

The collapse() method collapses the Range to one of its boundary points.

A collapsed Range is an empty range and doesn’t contain any content.



Syntax:

range.collapse(boolean);

Parameters: This method takes boolean value as parameter.



Return value: This method has no return value.

Example: This example shows how to collapse a range using this method. Collapsed property is used to check if the range is collapsed or not.




<!DOCTYPE html>
<html>
  
<head>
    <title>
        HTML DOM range 
        collapse() method
    </title>
</head>
  
<body>
    <h1>GeeksforGeeks</h1>
  
    <p>This is the Range Content</p>
  
    <button onclick="collapse()">
        Click To Collapse Range
    </button>
  
    <script>
        let range = document.createRange();
        let referenceNode = document.
            getElementsByTagName('p').item(0);
        range.selectNode(referenceNode);
        console.log("Before")
        console.log(range);
        console.log(range.collapsed);
        function collapse() {
            console.log("After")
            range.collapse(true);
            console.log(range);
            console.log(range.collapsed);
        }
    </script>
</body>
  
</html>

Output: In console, we can see that the range is collapsed using this method.

Supported Browsers: The browsers supported by DOM Range collapse() method are listed below:


Article Tags :