← Back toHTML DOM

Select the text content of an element

Written byPhuoc Nguyen
Level 1 — Basic
19 Apr, 2020
Last updated
18 Sep, 2023
Apart from clearing a contenteditable element, selecting all text within it can be useful in other situations as well. For instance, you may want to copy or delete all the text at once. Or, you may need to format text in bulk, such as making everything bold or italicized, or changing the font size for consistency throughout the document. Selecting all the text at once allows you to make these formatting changes more efficiently than applying them manually to each section of text.
Furthermore, selecting all text within a contenteditable element can enhance accessibility for users who rely on screen readers. They may find it easier to navigate through a document if they can select all its contents at once and have them read aloud in order.
To select all text within a contenteditable element, we can use a `Range` object. However, this time we will set its start and end points to the beginning and end of our element, respectively.
Here's an example function that selects all text within a contenteditable element:
const selectAllText = (contentEle) => {
const range = document.createRange();
const selection = window.getSelection();
First, we create a new `Range` object by calling `document.createRange()`. Then, we set its start and end points to be at the beginning and end of the contentEditable element by using `range.selectNodeContents(contentEle)`.
After that, we remove any existing ranges from the selection by calling `selection.removeAllRanges()`. Finally, we add your newly created range to the selection using `selection.addRange(range)`.
That's it! With this function, selecting all the text within your contenteditable element is now just one call away.

See also

Questions? 🙋

Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn