# contenteditable, template & Web Components

> Three powerful but often misunderstood native HTML features: `contenteditable` makes any element an in-place editor, `<template>` holds inert HTML ready to clone, and Web Components let you define your own reusable custom elements with encapsulated styles.

Subject: HTML | Lesson 42 of 42 | 8 min read
Interactive lesson: https://codewithanimation.in/html/contenteditable-template-web-components
Previous: [Native Overlays: dialog & popover](https://codewithanimation.in/html/dialog-and-popover.md)

## What these three features do

The `contenteditable` attribute makes any HTML element directly editable by the user in the browser -- not just `<input>` and `<textarea>`. Setting `contenteditable="true"` on a `<div>` or `<p>` gives it the same cursor, selection, and paste behaviour as a text input. The `input` event fires on every change, and `el.textContent` or `el.innerHTML` reads the current value. The `"plaintext-only"` value (Chromium-only) strips HTML formatting on paste, which is often what you want for editors that should not accept rich text.

The `<template>` element holds HTML markup that is completely inert: the browser parses it but does not render it and does not execute scripts or load images within it. The content is accessible as a `DocumentFragment` via `templateEl.content`. Clone it with `.cloneNode(true)` to produce a live DOM subtree you can modify and insert. This is the native alternative to building HTML strings in JavaScript.

Web Components is the umbrella term for three browser APIs: Custom Elements (define `<my-card>` as a class), Shadow DOM (an encapsulated DOM tree with scoped styles attached to any element), and HTML Templates (the `<template>` element above). Together they let you write self-contained, reusable components in plain HTML/JS/CSS with no framework required. Custom elements are registered with `customElements.define('my-card', MyCard)` where `MyCard extends HTMLElement`.

## When to use each one

`contenteditable` is the right tool for in-place editing UIs: comments that can be edited after posting, rich-text areas, inline renaming, and note-taking apps. It is not a replacement for `<textarea>` in forms: contenteditable elements do not participate in form submission (no `name`/`value`), do not support `maxlength`, and do not benefit from built-in browser spell-check in the same way. For simple text fields, use `<textarea>`.

`<template>` shines when the same chunk of HTML needs to be stamped out multiple times: table rows populated from JSON, notification toasts, card grids. Instead of building HTML strings (`innerHTML = '<div class...'`), which is an XSS risk and forces the browser to re-parse HTML, define the structure in `<template>` and clone it. Web Components use `<template>` to define their shadow DOM content declaratively.

## How to use them

For `contenteditable`: `<div contenteditable="true" role="textbox" aria-multiline="true" aria-label="Note"></div>`. Listen for `input` events to read changes. Add a CSS placeholder: `[contenteditable]:empty::before { content: attr(data-placeholder); color: #aaa; }`. Set `spellcheck="true"` explicitly if you want browser spell-check. Use `"plaintext-only"` in Chromium to strip paste formatting.

For `<template>`: define `<template id="card-tpl"><div class="card"><h3 class="card-title"></h3></div></template>`. Clone and populate: `const clone = document.getElementById('card-tpl').content.cloneNode(true); clone.querySelector('.card-title').textContent = 'Hello'; document.body.appendChild(clone);`.

For a custom element: `class MyCard extends HTMLElement { connectedCallback() { this.innerHTML = '<p>Hello</p>'; } } customElements.define('my-card', MyCard);`. Use it in HTML as `<my-card></my-card>`. For Shadow DOM, call `this.attachShadow({ mode: 'open' })` in the constructor and append children to `this.shadowRoot`.

## Common mistake: Using contenteditable for form inputs

The most common misuse of `contenteditable` is replacing `<input>` or `<textarea>` elements in forms because a designer wanted a styled text field. A `contenteditable` div does not submit with the form, does not support `required` or `maxlength`, cannot be validated with the Constraint Validation API, and requires manual JavaScript to capture the value and inject it into a hidden input. For form inputs, use actual form elements and style them with CSS.

## Tip: Web Components are framework-agnostic

A custom element defined with `customElements.define` works in any HTML page and inside any JavaScript framework -- React, Vue, Angular, Svelte, or none. The browser treats it as a first-class HTML element. This makes Web Components ideal for design systems that need to work across different framework projects. Frameworks that pass complex data via attributes (which can only be strings) need to use properties instead; most modern frameworks handle this.

## Try it: Try it

Type into a live `contenteditable` box, then stamp out cards from a `<template>` clone.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/html/contenteditable-template-web-components

## Check yourself

### Question 1

Why is contenteditable='true' a poor replacement for <textarea> in a form?

- A. It does not participate in form submission and does not support maxlength or built-in validation
- B. contenteditable elements cannot receive keyboard focus
- C. contenteditable is deprecated and should not be used in new code

Correct answer: A

A `contenteditable` element has no `name` or `value` in the form sense. It will not be included in form submission. Use `<textarea>` for form text fields and `contenteditable` for in-place editing UIs.

- Why not B: contenteditable elements do receive keyboard focus -- they behave like text editors. The problem is that they do not have a form value, so they do not submit.
- Why not C: contenteditable is a valid, modern HTML attribute. The problem is not deprecation but functional mismatch: it is an editor, not a form control.

### Question 2

What does 'inert' mean for content inside a <template> element?

- A. It is parsed but not rendered, scripts do not run, and images do not load until cloned
- B. It is rendered invisibly, like display:none
- C. It is only accessible in JavaScript, not visible in the HTML source

Correct answer: A

`<template>` content is parsed into a `DocumentFragment` that sits outside the rendered DOM. Scripts inside it do not execute, images do not load, and nothing is visible until you clone the content and append it to the document.

- Why not B: display:none hides content but it is still in the DOM and scripts still run. <template> content is never rendered and lives in a DocumentFragment outside the main DOM.
- Why not C: <template> content is visible in the HTML source (view-source shows it). It is inert meaning it is not rendered and does not execute, not that it is hidden from inspection.

### Question 3

Which lifecycle callback runs when a custom element is inserted into the document?

- A. connectedCallback
- B. constructor
- C. attributeChangedCallback

Correct answer: A

`connectedCallback()` fires each time the custom element is inserted into the document. It is the correct place to read attributes, render shadow DOM content, and attach event listeners.

- Why not B: The constructor runs when the element is created (before it is in the document). connectedCallback runs when the element is connected to the DOM -- the right place to set up DOM content and event listeners.
- Why not C: attributeChangedCallback runs when an observed attribute changes value. connectedCallback runs on insertion into the document.

## Remember this

- `contenteditable` makes any element editable in-place. It is not a form control -- use `<textarea>` for forms.
- `<template>` holds inert HTML. Clone with `.content.cloneNode(true)` to produce a live DOM subtree.
- Custom elements extend `HTMLElement` and are registered with `customElements.define('tag-name', Class)`.
- `connectedCallback` runs when the element enters the DOM; `attributeChangedCallback` runs on observed attribute changes.
