How to set selection by range in JavaScript?

Sometimes, we want to set selection by range in JavaScript.

In this article, we’ll look at how to set selection by range in JavaScript.

How to set selection by range in JavaScript?

To set selection by range in JavaScript, we can call the document.createRange and window.getSelection methods.

For instance, we write:

<p>
  hello world
</p>

to add a p element.

Then we write:

const node = document.querySelector("p").firstChild;
const range = document.createRange();
range.setStart(node, 0);
range.setEnd(node, 5); 

const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);

to select the text node with:

const node = document.querySelector("p").firstChild;

Next, we call document.createRange to create a range object.

And then we set the selection with setStart and setEnd.

Next, we call window.getSelection to get the selection.

And we call selection.removeAllRanges to clear existing selections.

Finally, we call selection.addRange with range to make the selection.

Conclusion

To set selection by range in JavaScript, we can call the document.createRange and window.getSelection methods.