The contains() method returns whether the specified element is a descendant of the current element or not. This is a very convenient method introduced by Internet Explorer to determine if an HTML element is descendant of another element. This method is useful for Internet Explorer version 9 and earlier.

The contains() method returns true if the specified element is found as a descendant and returns false if the element is not found in the descendant elements.

Syntax for contains() method

var isDescendant = container.contains (myButton);

compareDocumentPosition()

The compareDocumentPosition() method provides more flexible way of comparing the positions of two elements in Firefox, Opera, Google Chrome, Safari and Internet Explorer from version 9. The method determines the position of two nodes in a document and returns values describing their position. Possible return values and the node position are shown below:

  • 1: No relationship between nodes, they may belong to different documents.
  • 2: First node is positioned after second node.
  • 4: First node is positioned before second node.
  • 8: First node is positioned inside second node.
  • 16: Second node is positioned inside first node.
  • 32: No relationship or nodes are different attributes on same element. Return value can be combination of values. Like,
  • 20 (16 + 4): Second node is positioned inside first node and first node is positioned before second node.

Syntax for compareDocumentPosition() method

var relation = container.compareDocumentPosition (myButton);

In the example below, the contains() method is used to check if an HTML Element by id ‘myContainer’ has a descendant by id ‘nextButton’. The compareDocumentPosition() method is used to determine their positions.

Exampl of contains() and compareDocumentPosition() methods

 

›› go to examples ››