9

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

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Alan H.
  • 16,219
  • 17
  • 80
  • 113

2 Answers2

18

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

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • 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,351
  • 3
  • 21
  • 54
  • This doesn't select the text for me on Chrome. See my answer http://stackoverflow.com/a/25456308/227299 – Ruan 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