You are here: Reference > JavaScript > client-side > selection and ranges > methods > createTextRange (body, input, textarea, ...)

createTextRange method (body, input, textarea, ...)

Browser support:
Creates a new TextRange object and aligns its start and end points to the text content of the current element.
Note: the support for the createTextRange method has been removed in Opera 10.5.
Only the body and some other HTML elements support the createTextRange method. If you need to create a TextRange object that is adjusted to the contents of an element that does not support the createTextRange method, then use the createTextRange method on the body and invoke the moveToElementText method with the required element.
The TextRange object represents a contiguous part of the document. For further details, see the page for the TextRange object.
In Firefox, Opera, Google Chrome, Safari and Internet Explorer from version 9, the Range object provides functionality similar to the TextRange object. To create a new Range object, use the createRange method.


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

Return value:

Returns the newly created TextRange object.

Example HTML code 1:

This cross-browser example shows how the contents of an element can be deleted with range objects:
    <script type="text/javascript">
        function RemoveContent () {
            var srcObj = document.getElementById ("src");

            if (document.createRange) {     // all browsers, except IE before version 9
                var rangeObj = document.createRange ();
                rangeObj.selectNodeContents (srcObj);
                rangeObj.deleteContents ();
            else {      // Internet Explorer before version 9
                var rangeObj = document.body.createTextRange ();
                rangeObj.moveToElementText (srcObj);
                rangeObj.execCommand ('cut');
    <div id="src" style="background-color:#e0a0b0; width:300px; height:50px;">The <b>contents</b> of the <i>source</i> element.</div>
    <br /><br />
    <button onclick="RemoveContent ();">Remove the contents of the source element!</button>
Did you find this example helpful? yes no

Supported by objects:

Related pages:

External links:

User Contributed Comments

Post Content

Post Content