9

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?)

Alan H.
  • 15,651
  • 16
  • 76
  • 109

2 Answers2

16

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

Juan Mendes
  • 85,853
  • 29
  • 146
  • 204
  • 1
    awesome, fantastic that this does not require `contenteditable`. Also, major props for including a code snippet, spec references, working fiddle, links to more info! A+++ answer – Alan H. Aug 26 '14 at 00:00
3

select() Will only work on <input> and <textarea> elements...

Also yes, you will have to use:

contenteditable="true"

And use .focus() to select all the text.

Try this:

<p id="editable" contenteditable="true" 
onfocus="document.execCommand('selectAll',false,null);">Your Text Here</p>

<button onclick="document.getElementById('editable').focus();" >Click me</button>

JSFiddle Demo

imbondbaby
  • 6,253
  • 3
  • 18
  • 53
  • This doesn't select the text for me on Chrome. See my answer http://stackoverflow.com/a/25456308/227299 – Juan Mendes Aug 22 '14 at 22:21
  • Your jsFiddle only worked for me when the editable paragraph was already focused, which gave me the idea to use a window.setTimeout to allow the focus command to finish first. Success. Here's my fork of your fiddle: http://jsfiddle.net/alanhogan/nfqx0ex2/ – Alan H. Aug 25 '14 at 23:58