How can I: Select a paragraph with JavaScript (on click)?
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:
- The spec: http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level2-Range-method-selectNodeContents
- http://help.dottoro.com/ljcpcpnt.php
- https://developer.mozilla.org/en-US/docs/Web/API/range.selectNodeContents
- https://developer.mozilla.org/en-US/docs/Web/API/Selection.addRange
For support across all browsers, see https://github.com/timdown/rangy from https://stackoverflow.com/users/96100/tim-down
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