Select a paragraph with JavaScript (on click)?
Asked Answered
C

2

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

Culp answered 22/8, 2014 at 21:10 Comment(3)
Select it how? Select the content with .html() or .text(), or highlight the text as if you did with your mouse by dragging?Willem
@Willem Probably highlighting since the OP talked about selecting the contents of a an <input />Parenteral
https://mcmap.net/q/58040/-select-a-complete-table-with-javascript-to-be-copied-to-clipboard, https://mcmap.net/q/22266/-selecting-text-in-an-element-akin-to-highlighting-with-your-mouseAaronaaronic
P
20

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

Parenteral answered 22/8, 2014 at 22:16 Comment(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+++ answerCulp
A
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

Ayres answered 22/8, 2014 at 21:14 Comment(2)
This doesn't select the text for me on Chrome. See my answer https://mcmap.net/q/1130856/-select-a-paragraph-with-javascript-on-clickParenteral
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: jsfiddle.net/alanhogan/nfqx0ex2Culp

© 2022 - 2024 — McMap. All rights reserved.