You are here: Reference > JavaScript > client-side > selection and ranges > properties > commonAncestorContainer (Range)

commonAncestorContainer property (Range)

Browser support:
9
Returns a reference to the deepest node in the DOM hierarchy that contains the entire Range object.
Note: The Range object and its commonAncestorContainer property are supported in Internet Explorer from version 9.
In Internet Explorer before version 9 (and in newer ones as well), the TextRange object provides functionality similar to the Range object. To get the container element of a TextRange object, use the parentElement method.

Syntax:

object.commonAncestorContainer;
You can find the related objects in the Supported by objects section below.
This property is read-only.

Possible values:

Reference to the element that contains the entire Range object.
Default: this property has no default value.

Example HTML code 1:

This example illustrates the use of the commonAncestorContainer property:
<head>
    <script type="text/javascript">
        function GetSelectionContainer () {
            var container = null;
            if (window.getSelection) {  // all browsers, except IE before version 9
                var selectionRange = window.getSelection ();
                if (selectionRange.rangeCount > 0) {
                    var range = selectionRange.getRangeAt (0);
                    container = range.commonAncestorContainer;
                }
            } 
            else {
                if (document.selection) {        // Internet Explorer
                    var textRange = document.selection.createRange ();
                    container = textRange.parentElement ();
                }
            }

            if (container) {
                alert ("The name of the container node: " + container.nodeName);
            }
            else {
                alert ("Container object for the selection is not available!");
            }
        }
    </script>
</head>
<body>
    <table>
        <tr>
            <td>First row, first cell</td>
            <td>First row, second cell</td>
        </tr>
        <tr>
            <td>Second row, first cell</td>
            <td>Second row, second cell</td>
        </tr>
    </table>
    <br /><br />
    <button onclick="GetSelectionContainer ()">Get the container element for the selected text!</button>
</body>
Did you find this example helpful? yes no

Supported by objects:

Related pages:

External links:

User Contributed Comments

Post Content

Post Content