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

addRange method (selectionRange)

Browser support:
9
Adds a Range object to the current selection.
Note: The selectionRange object and its addRange method are supported in Internet Explorer from version 9.
The selectionRange object represents the current selection and every Range object that belongs to the selectionRange object represents a contiguous part of the selection.
In Internet Explorer, Opera, Google Chrome, Safari and Firefox before version 3, at most one Range can belong to the selectionRange object, because text selection is always a contiguous part of the DOM hierarchy.
In Firefox from version 3, multiple areas of text can be selected by holding down the CTRL key while selecting.
You can add ranges to the current selection with the addRange method, and remove them with the removeRange and removeAllRanges methods.
Since only Firefox supports more than one range for the selection, in other browsers, the addRange method does not add new ranges to the selection if it already contains one.
Use the getRangeAt method to get the Range objects that represent the current selection and the rangeCount property to get their count.

Syntax:

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

Parameters:

rangeToAdd
Required. Reference to the Range to add to the current selection.

Return value:

This method has no return value.

Example HTML code 1:

This example shows how to add a new range to the selection:
<head>
    <script type="text/javascript">
        function SelectFirstLine () {
            var elemToSelect = document.getElementById ("firstLine");
            if (window.getSelection) {  // all browsers, except IE before version 9
                var selection = window.getSelection ();
                var rangeToSelect = document.createRange ();
                rangeToSelect.selectNodeContents (elemToSelect);

                selection.removeAllRanges ();
                selection.addRange (rangeToSelect);
            } else {
                if (document.body.createTextRange) {    // Internet Explorer
                    var rangeToSelect = document.body.createTextRange ();
                    rangeToSelect.moveToElementText (elemToSelect);
                    rangeToSelect.select ();
                }
            }
        }
    </script>
</head>
<body>
    <button onclick="SelectFirstLine ();">Select the first line!</button>
    <br /><br />
    <div id="firstLine">This is the first line.</div>
    <div>This is the second line.</div>
</body>
Did you find this example helpful? yes no

Supported by objects:

Related pages:

External links:

User Contributed Comments

Post Content

Post Content