Firefox select text range

Quick question: How to programmatically select a text fragment of a page in FireFox? For example, there is a paragraph of text, the user presses a button and characters 10 through 15 are selected as if the user was dragging the mouse in the normal way.

+2


a source to share


2 answers


In Firefox, you can use the Range object as specified by the W3C .

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">   
    <title>Range test</title>
    <style>   
        #trigger { background: lightgreen }
    </style>                 
  </head>                    
  <body>                     
    <p id="test">This is some (rather short) text.</p>
    <span id="trigger">→ Click here! ←</span>
      <!-- Yes, I know, ‘Click here!’ is an evil message -->
    <script>
var testCase = function () {
    var userSelection;

    if (window.getSelection) {  // W3C default
        userSelection = window.getSelection();
    }  // an extra branch would be necessary if you want to support IE

    var textNode = document.getElementById('test').firstChild;
    var theRange = document.createRange();

    // select 10th–15th character (counting starts at 0)
    theRange.setStart(textNode, 9);
    theRange.setEnd(textNode, 14);

    // set user selection    
    userSelection.addRange(theRange);
};

window.onload = function () {
    var el = document.getElementById('trigger');
    el.onclick = testCase;
};
    </script>
  </body>
</html>

      



Note that you need to set TextNode

to select which is the firstChild

item <p>

. Also note that this example does not work in IE, you have to use some of your own methods. A good introduction is at QuirksMode .

+3


a source


I'm not sure if there is a way to do this for any DOM elements such as paragraphs, but for textarea elements, I believe you need to use selectionStart

and selectionEnd

and specify where to start and end.

var textarea = document.getElementsByTagName('textarea')[0];
textarea.selectionStart = 10;
textarea.selectionEnd = 15;

      



Hope this helps!

+1


a source







All Articles