Open In App

HTML DOM setRangeText() method

Improve
Improve
Like Article
Like
Save
Share
Report

The setRangeText() method replaces a range of text in input or a textarea with another string. 

Syntax:

element.setRangeText(replacement);

OR

element.setRangeText(replacement, start, end[, Mode]);

Parameters:

  • replacement: This parameter represents a string that will replace with the exits one.
  • Start: It specifies the index of the first character and it’s optional.
  • end: It specifies the index of character after the last start character it’s also optional.
  • Mode: This attribute defines how the selection should be set all the possible values are described below.
    • select: This will select the newly inserted text.
    • start: It will move the selected text before the newly inserted text.
    • end: Similar to start just move the selected text after the inserted text.
    • preserve: Preserve the selection and its default.

Example: In this example, we will use the setRangeText() method.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>
        DOM focus() Method
    </title>
    <style>
        a:focus {
            background-color: magenta;
        }
    </style>
</head>
   
<body>
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
    <h2>DOM select() Method</h2>
    <input type="text" id="text-box"
           size="40"
           value="A online Computer Science Portal.">
    <button onclick="selectText()">
        Update text
    </button>
   
    <script>
        //Main function
        function selectText() {
            const select =
                document.getElementById('text-box');
            select.focus();
            select.setRangeText
                (' For Geeks.', 32, 40, 'select');
        }
    </script>
</body>
 
</html>


Output: 

 

Supported Browsers: The supported browsers by HTML | DOM setRangeText() method are listed below:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Opera
  • Safari


Last Updated : 15 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads