HTML - DOM Element compareDocumentPosition() Method



The HTML DOM Element compareDocumentPosition() method is used to understand the document structure by comparing the positions of two DOM elements (nodes) and returns a bitmask.

A bitmask is a numeric value representing the position of the first element relative to the second element.

Syntax

Following is the syntax of the HTML DOM Element compareDocumentPosition() method −

node.compareDocumentPosition(otherNode);    

Parameters

This method accepts a single parameter as listed below −

Method Description
otherNode The other DOM node to compare against the original node.

Return Value

A bitmask indicating the positional relationship between the two DOM nodes. It's values and their meanings are as follows:

Relation Values & Description
Different Docs

1

Nodes belong to different documents
After

2

First node comes after the second
Before

4

First node comes before the second
Inside (1st)

8

First node is inside the second
Inside (2nd)

16

Second node is inside the first
Same Attributes

32

Nodes are attributes on the same element

Example 1: Comparing Elements in a Document

The following program demonstrates the usage of the HTML DOM Element compareDocumentPosition() by comparing two elements within the same document −




HTML DOM Element compareDocumentPosition()



HTML DOM Element compareDocumentPosition() method

Element 1
Element 2

The above program displays "Element 1 follows Element 2.", which means both the element having same document position.

Example 2: Comparing Element with it's Descendant

Here is another example of the HTML DOM Element compareDocumentPosition(). We compare the parent element with its child (descendant) element using this method −



 



HTML DOM Element compareDocumentPosition() Method

Compare Element with Descendant Example

Parent Element
Descendant Element

When the button clicks, it displays "Descendant contained by Parent Element" which means the the parent contains the specified element.

Example 3: Comparing Two Disconnected Elements

This example shows how to handle the case when two elements are compared but do not have any meaningful document relationship −




HTML DOM Element compareDocumentPosition()



HTML DOM Element compareDocumentPosition() Method

Supported Browsers

Method Chrome Edge Firefox Safari Opera
compareDocumentPosition() Yes Yes Yes Yes Yes
html_dom_element_reference.htm
Advertisements