Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

form elements

Selecting specific text in a textarea by BillyRayPreachersSon
Posted: 3 Dec 06 (Edited 3 Dec 06)

Note: This demo has been tested working in IE 6, and is known not to work in Firefox 1.5. Support for other browsers depends on whether they support createTextRange or not.

To search and select specific text, you need to create a text range. This can be done using the "createTextRange" method. Once done, you have many methods at your disposal, including "findText" and "select" which let you find and select text, as well as "moveStart" and "moveEnd" which let you control the textrange.

These methods are well documented on MSDN:






Here's a simple demo showing how to do it with a button press. I've added code to show how to "reset" the selection, too, once the end has been reached:


    <script type="text/javascript">

        var theRange = null;
        window.onload = function() {
            try {
                theRange = document.getElementById('myText').createTextRange();
            } catch(e) {}

            if (theRange == null) {
                alert('There was an error creating a textRange. Perhaps your browser doesn\'t support them.');

        function findNext() {
            if (theRange != null) {
                theRange.findText('[ ]');
                var charsMoved = theRange.moveStart('character', 3);
                if (charsMoved == 0) {
                    var startAgain = window.confirm('No more matches found. Start again from the beginning?');
                    if (startAgain) {
                        theRange.moveStart('textedit', -1);


        <textarea id="myText" cols="40" rows="5">Here is some text [ ], and here is some more [ ], and yet even more text! [ ]</textarea>
        <br />
        <input type="button" onclick="findNext();" value="Find next" />


Back to Javascript FAQ Index
Back to Javascript Forum

My Archive

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close