How to set cursor position on contentEditable div with JavaScript?

Spread the love

Sometimes, we want to set cursor position on contentEditable div with JavaScript.

In this article, we’ll look at how to set cursor position on contentEditable div with JavaScript.

How to set cursor position on contentEditable div with JavaScript?

To set cursor position on contentEditable div with JavaScript, we use the selectNodeContents method.

For instance, we write

const el = document.getElementById("idOfYoursContentEditable");
const selection = window.getSelection();
const range = document.createRange();
selection.removeAllRanges();
range.selectNodeContents(el);
range.collapse(false);
selection.addRange(range);
el.focus();

to select the div with getElementById.

Then we get the selection with getSelection.

Next, we create the selectionb range with createRange.

And we remove existing selection with removeAllRanges.

Next, we call selectNodeContents to set the selection.

Then we call addRange to make the selection.

Finally we call focus to focus on the element.

Conclusion

To set cursor position on contentEditable div with JavaScript, we use the selectNodeContents method.

Leave a Reply

Your email address will not be published.