How to set caret on a node in a contenteditable element

takechamp

Yusuke Takei

Posted on July 24, 2022

How to set caret on a node in a contenteditable element

Secret

You CANNOT set the caret on a contenteditable element only by foucs() on the element.

Code Sample

JavaScript

const setCaret = (
  contenteditableElement,
  node,
  position
) => {
  const selection = window.getSelection();
  if (!selection) return;

  // Create a new range
  const range = document.createRange();
  range.setStart(node, position);
  range.collapse(true);

  // Remove the current range
  selection.removeAllRanges();

  // Add the new range
  selection.addRange(range);

  // Focus on the contenteditable element instead of the node if needed.
  contenteditableElement.focus();
};
Enter fullscreen mode Exit fullscreen mode

TypeScript

const setCaret = (
  contenteditableElement: HTMLElement,
  node: Node,
  position: number
): void => {
  const selection = window.getSelection();
  if (!selection) return;

  // Create a new range
  const range = document.createRange();
  range.setStart(node, position);
  range.collapse(true);

  // Remove the current range
  selection.removeAllRanges();

  // Add the new range
  selection.addRange(range);

  // Focus on the contenteditable element instead of the node if needed.
  contenteditableElement.focus();
};
Enter fullscreen mode Exit fullscreen mode

Detail

range.collapse(true);
Enter fullscreen mode Exit fullscreen mode

sets Range.collapsed to true, which means the start and end points of the Range are at the same position.

References

💖 💪 🙅 🚩
takechamp
Yusuke Takei

Posted on July 24, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related