jQuery.contains() JQ Home  <<  Utilities  <<  jQuery.contains()

Inner DOM element detection.

Description

The jQuery.contains() jQuery General utility method, returns a boolean dependant upon whether a DOM element is within another DOM element.

Shorthand version $.contains()

  • The first argument to the jQuery.contains() jQuery General utility method must be a DOM element, not a jQuery object or plain JavaScript object.
  • Text and comment nodes are not supported.

Syntax

Signature Description
jQuery.contains( outer, inner )Return a boolean dependant upon whether a DOM element is within another DOM element.

Parameters

Parameter Description Type
outerThe DOM element that may contain inner.Element
innerThe DOM element that may be contained by outer.Element

Return

A Boolean object.

jQuery.contains( outer, inner ) Example Utilities  <<  Top

Return a boolean dependant upon whether a DOM element is within another DOM element.

In the example below when we press the button the first time we check to see if document.documentElement (the <html> tag) contains document.body (the <body> tag), which returns true. Then we check to see if document.body (the <body> tag) contains document.documentElement (the <html> tag), which returns false


$(function(){
  $('#btn9').one('click', function(){
    $('#div9').append('Does html contain body? : ' +
                       jQuery.contains( document.documentElement, document.body ) + '<br />');
    $('#div9').append('Does body contain html? : ' + 
                       jQuery.contains( document.body, document.documentElement ) + '<br />');
  });
});

div9. Some initial text.


Press the button below to action the above code:

Related Tutorials

jQuery Intermediate Tutorials - Lesson 9 - jQuery General Utilities