javascriptjqueryhtmldomtextselection

Select a paragraph with JavaScript (on click)?


Is it possible to select all the text of an element (e.g., a paragraph <p>) with JavaScript? A lot of people think jQuery .select() would do this, but it does not. It merely triggers an event. Note that DOM objects for <input> elements have a native select() method, but most other elements (such as <output> and <p>) do not.

(Do I need to use content-editable to get this to work?)


Solution

  • You can use Range.selectNodeContents

    document.querySelector('button').addEventListener('click', function(){
        var range = document.createRange();
        var selection = window.getSelection();
        range.selectNodeContents(document.querySelector('p'));
        
        selection.removeAllRanges();
        selection.addRange(range);
    });
                                              
                                              
                                              
                                              
    Hello <p>Select me</p> World
    <button id ='btn'>Select text</button>

    Related links:

    For support across all browsers, see https://github.com/timdown/rangy from https://stackoverflow.com/users/96100/tim-down