Why contenteditable fights you: syncing the DOM with state
With contenteditable, the browser changes the DOM before your code hears about it, so your state and the page drift apart. Here is how to read from the DOM, keep undo and the cursor in step, clean up legacy HTML, and handle selection across header, body and footer.
Manoj Mondal · · 4 min read
- #frontend
- #rich-text
- #contenteditable
Building a rich text editor on contenteditable is hard because two writers are editing the same page: your app and the browser.
Think of a shared whiteboard. You keep a neat copy of it in your notebook (your state). The browser is a second person who walks up and scribbles on the board whenever the user types, pastes or drags text. If you never look at the board again, your notebook slowly stops matching it. Every bug I have fought in editors comes back to this: the notebook and the board disagree.
The browser edits the DOM behind your back
In React, the usual rule is that state is the truth and the screen is drawn from it. With contenteditable, that flips: the user types, the browser changes the DOM first, and only then do you hear about it through an input event.
That creates three traps:
- Re-rendering wipes the cursor. If you rewrite the DOM from state after every keystroke, the browser throws away the caret position and the user's cursor jumps to the start.
- Fighting the browser loses. Overwriting its edit while it is mid-change (during IME composition, for example) breaks typing for languages like Japanese or Hindi.
- Different browsers write different HTML. The same Enter key can produce a
div, apor abrdepending on the browser and the surrounding markup.
The fix is a change of mindset. Treat the DOM as the working surface during typing, read from it on each input event, and write back to it only when you must (undo, programmatic formatting, loading content). Do not redraw on every keystroke.
In code, that looks like this:
const editor = document.querySelector<HTMLElement>('[contenteditable]')!;
let composing = false;
// Read from the DOM after the browser has already changed it.
const sync = () => { state.html = editor.innerHTML; }; // DOM -> state
editor.addEventListener('compositionstart', () => { composing = true; });
editor.addEventListener('compositionend', () => { composing = false; sync(); });
editor.addEventListener('input', () => { if (!composing) sync(); });
// Avoid this on every keystroke: it wipes the caret.
// editor.innerHTML = state.html;
Undo and redo: the cursor is part of the history
The browser has its own undo stack, but it only knows about edits it made itself. The moment your code changes the DOM (applying a heading, swapping a font size), that native history is out of step, and Ctrl+Z does something surprising.
So you build your own history. Each entry stores two things, not one:
- A snapshot of the content (or the change that was made).
- Where the cursor and selection were, as a path of child indexes plus a character offset, not as a live DOM node.
The second part matters most. Undo is like rewinding a video: if the picture rewinds but the playhead stays where it was, it feels wrong. A live DOM node reference dies when you restore old content, so a saved path ("third paragraph, fourth child, offset 12") is the only thing that survives. After restoring the content, walk that path and place the caret back.
Here is the save and restore pair, plus how an undo entry uses it:
type Point = { path: number[]; offset: number };
type SavedSelection = { start: Point; end: Point };
function pathTo(root: Node, node: Node): number[] {
const path: number[] = [];
while (node !== root) {
const parent = node.parentNode!;
path.unshift(Array.prototype.indexOf.call(parent.childNodes, node));
node = parent;
}
return path;
}
const nodeAt = (root: Node, path: number[]) =>
path.reduce<Node>((n, i) => n.childNodes[i], root);
function saveSelection(root: HTMLElement): SavedSelection | null {
const sel = getSelection();
if (!sel || sel.rangeCount === 0) return null;
const r = sel.getRangeAt(0);
return {
start: { path: pathTo(root, r.startContainer), offset: r.startOffset },
end: { path: pathTo(root, r.endContainer), offset: r.endOffset },
};
}
function restoreSelection(root: HTMLElement, s: SavedSelection) {
const range = document.createRange();
range.setStart(nodeAt(root, s.start.path), s.start.offset);
range.setEnd(nodeAt(root, s.end.path), s.end.offset);
const sel = getSelection()!;
sel.removeAllRanges();
sel.addRange(range);
}
// Each history entry carries both content and cursor.
undoStack.push({ html: editor.innerHTML, selection: saveSelection(editor) });
// Undo
const entry = undoStack.pop()!;
editor.innerHTML = entry.html;
if (entry.selection) restoreSelection(editor, entry.selection);
Old HTML in, clean HTML out
Content rarely starts clean. Pasted text and older documents bring legacy tags like <font size="3">, whose sizes are the numbers 1 to 7 and mean nothing in pixels. If you leave them in, every size feature you build has to understand two systems.
My approach is to normalize on the way in: map each legacy size to a real value and replace the tag with a <span style="font-size: ...">. Now the document has one way to express size, and your toolbar, your undo history and your export all read the same thing.
A small version of that border check:
// Typical browser defaults for the legacy 1-7 scale.
const FONT_SIZE_PX: Record<number, number> = {
1: 10, 2: 13, 3: 16, 4: 18, 5: 24, 6: 32, 7: 48,
};
function normalizeFontTags(root: HTMLElement) {
root.querySelectorAll('font[size]').forEach((font) => {
const span = document.createElement('span');
const px = FONT_SIZE_PX[Number(font.getAttribute('size'))];
if (px) span.style.fontSize = `${px}px`;
span.append(...font.childNodes); // keep the children, drop the tag
font.replaceWith(span);
});
}
It works like a customs desk. Foreign goods can enter, but they are converted to the local currency at the border, so nothing inside the country has to deal with exchange rates.
Header, body and footer: one selection, three editors
A document with a header, body and footer usually means three separate editable regions. The browser keeps only one selection at a time, and it belongs to whichever region has focus.
That raises questions you have to answer yourself:
- When the user clicks the toolbar, focus leaves the editor. Where does the "current selection" live while they pick a font size?
- When they switch from body to footer, which region does Undo apply to?
- If a command runs on the wrong region, it formats text the user never selected.
The pattern that worked for me is to save the last known selection per region, and to track which region is active. The toolbar then acts on that saved selection and restores focus afterwards. It is like a bookmark in each of three books: you always know which book is open and where you stopped reading.
A minimal version of the bookmark idea:
const regions = { header, body, footer } as Record<string, HTMLElement>;
const saved = new Map<string, SavedSelection>();
let active = 'body';
// Runs on every caret move, so the bookmark is always fresh.
document.addEventListener('selectionchange', () => {
const anchor = getSelection()?.anchorNode ?? null;
for (const [name, el] of Object.entries(regions)) {
if (anchor && el.contains(anchor)) {
active = name;
const s = saveSelection(el);
if (s) saved.set(name, s);
}
}
});
// Toolbar commands always run against the remembered region.
function runOnActive(command: (el: HTMLElement) => void) {
const el = regions[active];
el.focus();
const s = saved.get(active);
if (s) restoreSelection(el, s);
command(el);
}
What to remember
- Don't re-render the DOM on every keystroke. Read from it, and write back only when needed.
- Build your own undo history, and store the cursor with every entry as a path, not a node.
- Normalize messy input once, at the border, so the rest of the editor has one format to deal with.
- With several editable regions, track the active region and save a selection for each.
The common thread is to decide who owns the truth at each moment, you or the browser, and never let both write at once.