You are here: Reference > JavaScript > client-side > HTML DOM > methods > contains

contains method

Browser support:
Returns whether the specified element is a descendant of the current element.
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.
If you need a complex comparison method for elements in Internet Explorer, create TextRange objects from the elements first (see the createTextRange and moveToElementText methods) and use the compareEndPoints method on them.

Syntax:

object.contains (element);
You can find the related objects in the Supported by objects section below.

Parameters:

element
Required. Reference to the element to compare.

Return value:

Boolean. One of the following values:
false The specified element is not contained by the current element.
true The specified element is contained by the current element.

Example HTML code 1:

This example illustrates the use of the contains method:
<head>
    <script type="text/javascript">
        function IsDescendantOfContainer (button) {
            var container = document.getElementById ("container");
            var isDescendant = false;
            if (container.compareDocumentPosition) {
                var relation = container.compareDocumentPosition (button);
                isDescendant = ((relation & Node.DOCUMENT_POSITION_CONTAINED_BY) != 0);
            }
            else {  // Internet Explorer before version 9
                isDescendant = container.contains (button);
            }

            if (isDescendant) {
                alert ("The button is a descendant of the container element.");
            }
            else {
                alert ("The button is not a descendant of the container element.");
            }
        }
    </script>
</head>
<body>
    <div id="container" style="width:300px;height:100px;background-color:#e0c0a0;">
        This text is inside the container element.
        <br /><br /><br />
        <button onclick="IsDescendantOfContainer (this);">Is this button a descendant of the container?</button>
    </div>
</body>
Did you find this example helpful? yes no

Supported by objects:

Related pages:

External links:

User Contributed Comments

Post Content

Post Content