Open In App

HTML DOM Range compareBoundaryPoints() method

Improve
Improve
Like Article
Like
Save
Share
Report

The compareBoundaryPoints() method is used to compare the boundary points of the one Range with the boundary points of another range.

Syntax:

compare = firstRange.compareBoundaryPoints(comparision_method, otherRange);

Return Value: This method returns a number indicating the position of boundary points:

  • -1 : returns -1 if boundary point of 1st range lies before the boundary point of 2nd range.
  • 0 :  returns 0 if boundary point of 1st range lies equal to the boundary point of 2nd range.
  • 1 :  returns 1 if boundary point of 1st range lies after the boundary point of 2nd range.

Parameters: This method contain 2 parameters:

1. A constant describing the comparison method:

  • Range.END_TO_END to compare the end boundary-point of 1st Range to the end boundary-point of 2nd Range.
  • Range.END_TO_START compares the end boundary-point of 1st Range to the start boundary-point of 2nd Range.
  • Range.START_TO_END compares the start boundary-point of 1st Range to the end boundary-point of 2nd Range.
  • Range.START_TO_START compares the start boundary-point of 1st Range to the start boundary-point of 2nd Range.

2. otherRange : Other range for comparison.

Example: In the example, we will create and compare two ranges.

HTML




<html>
<head>
<title>HTML DOM range compareBoundaryPoints() method</title>   
</head>
<body>
    <h1>GeeksforGeeks</h1>
    <div>This is the Range 1 Content</div>
    <div>This is the Range 2 Content</div>
</body>
<script>
    var range1, range2, compare;
  range1 = document.createRange();
  range1.selectNode(document.getElementsByTagName("div")[0]);
  console.log(range1);
  range2 = document.createRange();
  range2.selectNode(document.getElementsByTagName("div")[1]);
  console.log(range2);
  compare = range1.compareBoundaryPoints(Range.START_TO_END, range2);
  console.log(compare);
</script>
</html>


Output: In console, we can see the logged comparison of both the ranges along with those ranges.

output is -1, as startOffset of range1 is 3 and is before the endOffset of range2 is 6.

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

  • Google Chrome
  • Edge
  • Firefox
  • Safari
  • Opera
  • Internet Explorer

Last Updated : 30 Jun, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads