HTML DOM Range compareBoundaryPoints() method

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

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


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

full-stack-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.