How can I: Select a paragraph with JavaScript (on click)?

Alan H. picture Alan H. · Aug 22, 2014 · Viewed 9.5k times · Source

Is it possible to select all the text an 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?)

Answer

Juan Mendes picture Juan Mendes · Aug 23, 2014

If you need to support later browsers, i.e., IE9+, you can use the following

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