HTML: the contenteditable attribute
The contenteditable attribute lets a user edit an element's content directly in the browser.
What you will learn
- How to make an element editable with
contenteditable - How to make editing state, focus, and keyboard use understandable
- Why content must be validated and sanitized before it is saved
Basic example
<label for="note">Edit your note</label>
<div id="note" contenteditable="true" role="textbox" aria-multiline="true">
Write a note here.
</div>
<button type="button">Save note</button>
The value true makes the element editable. Give the area a visible label and make the save action clear; a custom editing surface should expose the behavior users need.
Editing state
<div contenteditable="false">Read-only text</div>
<div contenteditable="true" spellcheck="true">Editable text</div>
The attribute can be true, false, or plaintext-only where supported. Test the behavior in your target browsers, and do not assume that a rich editing surface behaves like a normal text input.
Save safely
Contenteditable content can contain markup and unexpected input. Before saving or displaying it for other users, validate the data on the server and sanitize HTML with a trusted, context-aware solution. Never treat browser HTML as trusted input.
Common mistakes
- Making text editable without a label or an obvious save action.
- Assuming
contenteditableautomatically saves content to a server. - Rendering user-entered HTML without sanitizing it.
- Using a complex editor when a native input or textarea would be enough.