HTML & CSSMedium
What is contenteditable?
contenteditable is a global attribute that makes an element's content directly editable by the user, like a mini text editor in the page. It is the foundation of rich-text editors such as Notion, Google Docs-style tools, and libraries like ProseMirror, Lexical, Slate and TipTap.
Values
contenteditable="true"(or empty): fully editable, including pasted formatting.contenteditable="plaintext-only": editable but strips rich formatting (now supported in all major browsers).contenteditable="false": makes a region inside an editable area read-only.
Working with it
- Listen to
inputevents and readel.textContentorel.innerHTML. beforeinputlets you inspect or cancel an edit before it happens (e.inputType).- The Selection and Range APIs control the caret and selected text.
document.execCommandis deprecated; editors implement formatting themselves.
Pitfalls
- Security: pasted HTML can include scripts or event handlers. Sanitize (e.g. DOMPurify) before saving or rendering it elsewhere.
- Inconsistent markup across browsers (
<div>vs<br>on Enter), which is why real editors use a document model. - Accessibility: add
role="textbox",aria-multiline="true"and a label so assistive tech knows it is an input. - Not a form control: it is not submitted with forms; copy its value into a hidden input yourself.
Interview tip
Say you would reach for a battle-tested editor library for anything beyond simple inline editing.
Code example
html
1<style>2 body { font-family: system-ui; }3 .editor { border: 2px solid #0b1020; border-radius: 8px; padding: 10px; min-height: 60px; }4 .editor:focus { outline: 3px solid #2b4bff; }5</style>6<label id="lbl">Bio (plain text only)</label>7<div class="editor" contenteditable="plaintext-only" role="textbox" aria-multiline="true" aria-labelledby="lbl">8 Frontend developer who loves accessible UI.9</div>10<p>Characters: <output id="count">0</output></p>11<script>12 const editor = document.querySelector(".editor");13 const update = () => (document.getElementById("count").textContent = editor.textContent.trim().length);14 editor.addEventListener("input", update);15 // Block edits beyond 140 characters before they happen16 editor.addEventListener("beforeinput", (e) => {17 if (e.inputType.startsWith("insert") && editor.textContent.length >= 140) e.preventDefault();18 });19 update();20</script>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.