How to select all text in an element with Javascript

/

April 02, 2020

TLDR

js
1.window.getSelection().selectAllChildren(element);

Get Selection Object

The Selection object is part of the Web API and deals with the selection of text in browsers. You can get a selection object using the getSelection() method on the window object:

js
1.window.getSelection();

Select All Element Text

The selectAllChildren() is a method on the Selection object that selects all the text of all children elements for a specific element. Pass the element you want to select the contents of and the browser will automatically select the text.

js
1.window.getSelection().selectAllChildren(element);

Example

html
1.<blockquote id="quote20">
2. “People say nothing is impossible, but I do nothing every day.” – A. A. Milne
3.</blockquote>
4.<button id="copyQuote">Copy</button>
js
1.const blockquote = document.getElementById("quote20");
2.const button = document.getElementById("copyQuote");
3.
4.button.addEventListener("click", e => {
5. window.getSelection().selectAllChildren(blockquote);
6.});