How to set or change the user’s text selection in JavaScript?

Sometimes, we want to set or change the user’s text selection in JavaScript.

In this article, we’ll look at how to set or change the user’s text selection in JavaScript.

How to set or change the user’s text selection in JavaScript?

To set or change the user’s text selection in JavaScript, we can use the browser selection API.

For instance, we write:

<p>
  hello world
</p>

to add a p element.

Then we write:

const selection = window.getSelection()
const p = document.querySelector('p')
selection.setBaseAndExtent(p, 0, p, 1)

to call window.getSelection to get the selection object.

Then we call selection.setBaseAndExtent to make the select with p to make selections in the p element.

The first argument is the node at the start of the selection.

The 2nd argument is the number of child nodes from the start of the anchor node that should be excluded from the selection.

The 3rd argument is the node at the end of the selection.

And then last argument is the number of child nodes from the start of the node in the 3rd argument that should be included in the selection.

Conclusion

To set or change the user’s text selection in JavaScript, we can use the browser selection API.