JavaScript compareDocumentPosition() Method Tutorial

In this section, we will learn what the Element compareDocumentPosition() method is and how to use it in JavaScript.

What is Element compareDocumentPosition() Method in JavaScript?

The JavaScript Element compareDocumentPosition() method is used to get the relationship (position-wise) between two elements.

For example, if we want to see if an element is the child of another one or if it’s coming after another element or before that element, etc. this method can help us to do that.

Element compareDocumentPosition() Method Syntax:

element.compareDocumentPosition(targetElement)

Element compareDocumentPosition() Method Parameter

The method takes one argument and that is a reference to the target element that we want to compare the current element (the one that invoked the method) with.

Element compareDocumentPosition() Method Return Value

The return value of this method is an integer and could be either of these values:

1: The value 1 means there’s no relation between elements because these nodes don’t belong to the same document.

2: This value means the first node (the one that invoked the method) comes after the second node (the argument node).

4: This value means the first node (the one that invoked the method) comes before the second node (the argument node)

8: This value means the first node is positioned inside the body of the second node.

16: This value means the second node is positioned inside the body of the first node.

32: This value means there’s no relationship between the two nodes or these nodes are two attribute nodes belonging to the same element.

Note: the return value of this method might be a combination of the values mentioned above. For example, the value 20 means the same as the value 16.

Example: using compareDocumentPosition() method in JavaScript

See the Pen using compareDocumentPosition() method in JavaScript by Omid Dehghan (@odchan1) on CodePen.

Leave a Reply