You are here: Reference > JavaScript > client-side > selection and ranges > methods > parentElement (TextRange)

parentElement method (TextRange)

Browser support:
10.5
Returns a reference to the deepest node in the DOM hierarchy that contains the entire TextRange object.
In Firefox, Opera, Google Chrome and Safari, the Range object provides similar functionality to the TextRange object. Internet Explorer also supports the Range object from version 9.
Use the commonAncestorContainer property in those browsers to get the container element of a Range object.

Syntax:

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

Return value:

Returns the container object.

Example HTML code 1:

This example illustrates the use of the parentElement method:
<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