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

  • element1 and element2: 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

  • HTML
Console

Explanation

  • In line 5, we create a paragraph tag with id element1 and display text.

  • In line 6, we create a paragraph tag with id element2 to display text.

  • In line 8, we create a paragraph tag to display text.

  • In line 10, we write a button tag with a change() function bound with the onclick event.

  • In line 13, we write the JavaScript code in the script tag and define the change() function, which will be called by the click of a button from the HTML page.

  • In line 14, we use document.getElementById() to get the element of id element1 and store it in variable element1.

  • In line 15, we use document.getElementById() to get the element of id element2 and store it in variable element2.

  • In line 16, we apply the compareDocumentPosition() method on element2 and pass element1 as 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.

Free Resources