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?)
select() The HTMLInputElement. select() method selects all the text in a <textarea> element or in an <input> element that includes a text field.
The most basic of the selectors is an element selector. For example, paragraphs in an HTML document are represented by the p element and wrapped in <p></p> tags. To select all paragraphs in a document we would use the following selector. To select all level 1 headings we would use the h1 selector.
To interact with <select> element in JavaScript, you use the HTMLSelectElement type. The HTMLSelectElement type has the following useful properties: selectedIndex – returns the zero-based index of the selected option. The selectedIndex is -1 if no option is selected.
getElementsByTagName() that will select all the instances of a certain HTML element on the current webpage based on its tag name, i.e. <div> . Calling document. getElementsByTagName("div") is all you need to do to select all <div> elements on the current page using JavaScript.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With