What is the DOM compareDocumentPosition() method?
Overview
In this shot, we will learn how to compare elements by their position in the DOM. The compareDocumentPosition() method is applied on an element, and another element is passed as a parameter.
Syntax
element1.compareDocumentPosition(element2)
Parameters
element1andelement2: The variables to be compared.
Return value
This method returns a value that can be any of the following:
| Return value | Meaning |
|---|---|
1 |
The elements do not have any relation to each other. |
2 |
element1 is positioned after element2. |
4 |
element1 is positioned before element2. |
8 |
element1 is positioned inside element2. |
16 |
element2 is positioned inside element1. |
32 |
element1 and element2 are in the same node. |
Example
Explanation
-
In line
5, we create a paragraph tag withidelement1and display text. -
In line
6, we create a paragraph tag withidelement2to display text. -
In line
8, we create a paragraph tag to display text. -
In line
10, we write a button tag with achange()function bound with theonclickevent. -
In line
13, we write the JavaScript code in thescripttag and define thechange()function, which will be called by the click of a button from the HTML page. -
In line
14, we usedocument.getElementById()to get the element ofidelement1and store it in variableelement1. -
In line
15, we usedocument.getElementById()to get the element ofidelement2and store it in variableelement2. -
In line
16, we apply thecompareDocumentPosition()method onelement2and passelement1as a parameter. A number will be returned, as discussed in the table.
We get 2 as a return value, which means that elem2 is positioned after elem1.