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.
- true: Collapses the Range to its start.
- false: Collapses the Range to its end.
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.
HTML
<!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.
-
Before Clicking the Button:
-
After Clicking the Button:
It can be seen that start Offset and en Offset are now set to 3 after collapsing
Supported Browsers: The browsers supported by DOM Range collapse() method are listed below:
- Google Chrome
- Edge
- Firefox
- Safari
- Opera
Recommended Posts:
- Collect.js | collapse() Method
- HTML DOM Range selectNodeContents() Method
- HTML DOM Range cloneContents() method
- HTML DOM Range setEndBefore() method
- HTML DOM Range compareBoundaryPoints() method
- HTML DOM Range selectNode() method
- HTML DOM Range deleteContents() Method
- HTML DOM Range setEnd() Method
- HTML DOM Range toString() Method
- HTML DOM Range setStartBefore() Method
- HTML DOM Range setEndAfter() Method
- HTML DOM Range extractContents() Method
- HTML DOM Range setStart() Method
- HTML DOM Range cloneRange() Method
- HTML DOM Range insertNode() Method
- HTML | DOM Input Range stepUp() Method
- HTML | DOM Input Range stepDown() Method
- CSS Margin Collapse
- Bootstrap 4 | Collapse
- CSS | border-collapse Property
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


