JavaScript Answers

How to Select Text in an Element Programmatically Like Highlighting with a Mouse?

Spread the love

The window.getSelection Method

We can use the window.getSelection method to select text in an element.

For instance, if we have the following HTML:


Then we call window.getSelection by writing:

const node = document.querySelector('div');  
if (window.getSelection) {  
  const selection = window.getSelection();  
  const range = document.createRange();  

We call window.getSelection to create the seldction object.

Then we call document.createRange to create the select range.

And then we call range.selectNodeContents with the node object to select the content of the given element.

Next, we call selectionRemoveAllRanges to remove all previously selected content.

Finally, we call selection.addRange with the range to select the currently selected text.

The window.getSelection method available with non-Internet Explorer browsers.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *