Alan H.
Alan H.

Reputation: 16568

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

Upvotes: 9

Views: 13532

Answers (2)

Ruan Mendes
Ruan Mendes

Reputation: 92274

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

Upvotes: 21

imbondbaby
imbondbaby

Reputation: 6411

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

Upvotes: 3

Related Questions