JavaScript Answers

How to set cursor position on contentEditable div with JavaScript?

Spread the love

To set the cursor position within a contentEditable <div> element using JavaScript, you can utilize the Selection object.

For example, we write:

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Set Cursor Position in contentEditable DIV</title>

<div id="editableDiv" contenteditable="true">This is a contentEditable div. Click here to edit.</div>

    // Function to set cursor position
    function setCursorPosition(element, position) {
        var range = document.createRange();
        var sel = window.getSelection();
        range.setStart(element.childNodes[0], position);

    // Usage: Set cursor position to the end
    var editableDiv = document.getElementById('editableDiv');
    setCursorPosition(editableDiv, editableDiv.textContent.length);


In this example, we define a function setCursorPosition(element, position) that takes an HTML element (contentEditable div in this case) and a position as arguments.

Inside the function, we create a Range object and a Selection object.

Then, we set the start of the range to the specified position within the child node of the element (assuming it’s a text node).

Next we collapse the range to the specified position.

We remove all existing ranges from the selection and add the newly created range.

Finally, we focus on the contentEditable element to make the cursor appear at the specified position.

In the usage part, we call this function with the contentEditable div element and the length of its text content to set the cursor position to the end. You can adjust the position as needed.

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 *