Ways to render a component
Compare innerHTML vs template cloning in web components, update only the parts that changed, and keep HTML from users safe with setHTML() and Trusted Types.
- 01Say what each way costsCompare
innerHTML, a fresh clone, and targeted updates, and show what a full redraw throws away. - 02Update only what changedKeep references to the parts that change, write a value only when it differs, and reuse list rows by key.
- 03Keep HTML from data safeSpot the markup that runs code, and use
textContent,setHTML(), and Trusted Types instead of strings.
What are the ways to render a web component?
Ravi built a brewing card for the counter at Leaf and Kettle. It counts down the seconds while a tea steeps. Under the countdown is a box for a tasting note. Asha tries it with an Oolong. She starts typing "Floral", and before she finishes, the word is gone.
"Every second, my note disappears," she says. "Is the card broken?" Ravi has a second worry. Customers want to post reviews with bold words in them. Can a card show those safely?
A web component can render in three ways. It can set innerHTML from a string, clone a template it parsed once, or keep references to the parts that change and update only those. innerHTML is the simplest, but it rebuilds every node on every update, so typed text, focus, and listeners are lost. For HTML from users, use setHTML(), which removes anything that could run code.
Here is Ravi's card. Click in the box in the result, and type a note:
<tea-brew></tea-brew> <script> class TeaBrew extends HTMLElement { left = 30; constructor() { super(); this.attachShadow({ mode: "open" }); } connectedCallback() { this.render(); setInterval(() => { if (this.left > 0) this.left -= 1; this.render(); }, 1000); } render() { this.shadowRoot.innerHTML = `<p>Oolong: ${this.left} s</p> <input aria-label="Tasting note">`; } } customElements.define("tea-brew", TeaBrew);</script>- Line 1 puts the card on the page. Line 5 starts its countdown at 30 seconds.
- Line 9 gives the card a shadow root, as in lesson 6.1.
- Lines 14 to 17 run every second. Line 15 counts down until it reaches 0. Line 16 draws the card again.
- Lines 21 and 22 are the drawing. They set the shadow root's
innerHTMLto a string with the seconds in it.
Within a second, your note is gone, and the cursor has left the box. Line 21 runs on every tick. Each time, it throws away the old box and builds a new, empty one. It even does this at 0 seconds, when nothing on the card changes.
innerHTML throws away both old nodes, and the note typed in the box goes with them. Then it builds two new nodes from the string. The new box is empty.Leaf and Kettle writes its specials on a chalkboard. A new helper needs to change one price. So she wipes the whole board and writes everything out again. A customer had written her name in the corner to hold a table. That's wiped too.
- In real life: Wiping the whole board
- In JavaScript: Setting
innerHTML, which removes every old node - In real life: Writing it all out again
- In JavaScript: Parsing the string and building new nodes
- In real life: A name written in the corner
- In JavaScript: The note typed in the box
- In real life: Changing only the one number
- In JavaScript: Updating only the part that changed
There are three ways to render: an HTML string, a template copy, and updating only what changed. Only the last one keeps every node that didn't change. Data never goes into an HTML string. HTML from users goes through setHTML().
This lesson takes each way in turn: what it costs, what it throws away, and when it's safe. It builds on two lessons on the JavaScript path, Creating & changing elements and XSS & safe DOM updates.
What happens when a component renders with innerHTML?
Setting innerHTML does two jobs. First, the browser hands the string to its HTML parser, which builds new nodes. Then it removes every child the shadow root had, and puts the new ones in their place. MDN says the same: it parses the value and replaces all the descendants.
Nothing old is kept, even when the markup hardly changes. This card draws, takes a note, and draws again:
<div id="card"></div> <script> const root = document.querySelector("#card").attachShadow({ mode: "open" }); function render(left) { root.innerHTML = `<p>Oolong: ${left} s</p> <input aria-label="Tasting note"> <button>Done</button>`; } render(30); const box = root.querySelector("input"); box.value = "Floral"; root.querySelector("button").addEventListener("click", () => console.log("Done!")); render(29); console.log(box === root.querySelector("input")); console.log(box.isConnected); console.log(root.querySelector("input").value.length); root.querySelector("button").click();</script>- Lines 6 and 7 are the drawing: a line of text, a box, and a Done button.
- Line 12 puts
Floralin the box, the way typing would. Line 13 gives the button a click listener. - Line 15 draws the card again, with 29 seconds.
- Line 16 prints
false. The box in the card now is a different element. - Line 17 prints
false. The old box isn't in the page anymore. - Line 18 prints
0. The new box is empty. - Line 19 clicks the new button. Nothing prints. The listener was on the old button.
Everything that lived on the old nodes goes with them. That means typed text, focus, and listeners. It also means two more things: a text selection disappears, and a box that was scrolled jumps back to the top. Lesson 7.2's redraw playground showed the same loss with template copies.
Quotes in the data
There's a second problem. Data glued into a string can break the markup around it. Here, a tea's name goes into a title:
<div id="card"></div> <script> const name = `Asha's "Big" blend`; const root = document.querySelector("#card").attachShadow({ mode: "open" }); root.innerHTML = `<h3 title="${name}">${name}</h3>`; const heading = root.querySelector("h3"); console.log(`[${heading.title}]`); console.log(heading.getAttributeNames().join(" "));</script>- Line 4 is a name with an apostrophe and two double quotes.
- Line 6 puts the name in two places: inside the
titleattribute's quotes, and as the heading's text. - Line 8 prints the title in square brackets:
[Asha's ]. The attribute ended at the first double quote. - Line 9 prints
title big" blend". The rest of the name became two new attributes.
The heading's text looks right, so the bug is easy to miss. Hover over it in the result, and the tip says only Asha's. Setting the title with setAttribute() avoids the bug, because an attribute's value is never parsed, as lesson 7.2 showed.
Why it matters: innerHTML is fine for markup you wrote, set once. Use it to redraw, and it rebuilds everything and loses what the user was doing. Use it with data, and the data can change the markup.
Is cloning a template faster than innerHTML?
The second way is a template. Parse the markup once into a <template>, and give each element a copy with cloneNode(true). Yes, that's faster for the first render. Chrome's guidance calls cloning a parsed template "far faster" than parsing an innerHTML string for every element, as lesson 7.1 showed.
And against building the same nodes one by one, with createElement()? Nolan Lawson measured that. In his benchmark, cloning a template was about 50% faster in Chrome, 15% faster in Firefox, and 10% faster in Safari. He notes that the gap changes with the size of the markup.
But a template only saves the parsing. If render() clones a fresh copy on every update, every node is still new. This playground counts the elements each tick builds, in three versions of the countdown:
<tea-brew></tea-brew> <script> const template = document.createElement("template"); template.innerHTML = `<p>Oolong: <span></span> s</p><input aria-label="Tasting note">`; class TeaBrew extends HTMLElement { left = 5; constructor() { super(); this.attachShadow({ mode: "open" }); } connectedCallback() { this.render(); setInterval(() => this.tick(), 1000); } tick() { if (this.left === 0) return; const old = new Set(this.shadowRoot.querySelectorAll("*")); this.left -= 1; this.render(); const made = [...this.shadowRoot.querySelectorAll("*")].filter((element) => !old.has(element)); console.log(`${this.left} s: ${made.length} new elements`); } render() { this.shadowRoot.innerHTML = `<p>Oolong: <span>${this.left}</span> s</p> <input aria-label="Tasting note">`; } } customElements.define("tea-brew", TeaBrew);</script>Each tick hands the whole string to the HTML parser. The <p>, the <span>, and the note box are all new, so the console prints 3 new elements five times. A note you type is gone after the next tick.
- innerHTML every tick prints
3 new elementson every tick: the<p>, the<span>, and the box. - A fresh clone every tick prints
3 new elementstoo. Nothing was parsed, but the copy is all new. - Clone once, then set the text prints
0 new elements. Line 30 checks whether the card has its copy yet. Lines 31 and 32 clone it once and keep the<span>. After that, line 34 only sets the seconds.
Lines 22 and 25 do the counting. Line 22 remembers every element before the tick. Line 25 keeps the ones it hasn't seen before. Type a note in each version too. It survives only in the third.
Why it matters: cloning makes the first render cheap. To make every update cheap too, keep the copy, and change only what changed.
How do you update only what changed?
The third way has two parts:
- Keep a reference to each element that shows a value.
- On every render, compare each new value with the one on screen, and write only the ones that differ.
Leaf and Kettle's newer menu board has slots. Each price is printed on a small card that slides in. To change Oolong's price, Ravi slides out one card and slides in another. Everything else on the board stays put. If the new price is the same as the old one, he doesn't touch the board at all.
- In real life: The board with slots, put up once
- In JavaScript: The shadow root, cloned once from a template
- In real life: Each slot
- In JavaScript: A saved reference, like
this.#parts.left - In real life: Sliding in a new card
- In JavaScript: Setting
textContenton that one element - In real life: Leaving the board alone when the price is the same
- In JavaScript: Skipping a value that didn't change
Here is the countdown card with a render() that compares:
<tea-brew></tea-brew> <script> const template = document.createElement("template"); template.innerHTML = `<p><b></b>: <span></span> s</p><input aria-label="Tasting note">`; class TeaBrew extends HTMLElement { #parts = {}; #shown = {}; constructor() { super(); this.attachShadow({ mode: "open" }).append(template.content.cloneNode(true)); this.#parts.tea = this.shadowRoot.querySelector("b"); this.#parts.left = this.shadowRoot.querySelector("span"); } render(state) { for (const key of ["tea", "left"]) { if (state[key] === this.#shown[key]) continue; this.#parts[key].textContent = state[key]; console.log(`Wrote ${key}`); } this.#shown = { ...state }; } } customElements.define("tea-brew", TeaBrew); const brew = document.querySelector("tea-brew"); brew.render({ tea: "Oolong", left: 30 }); brew.render({ tea: "Oolong", left: 29 }); brew.render({ tea: "Oolong", left: 29 });</script>- Lines 4 and 5 make the template once.
- Line 13 clones it into the shadow root, once, in the constructor. That's allowed: the constructor may fill its own shadow root. Lesson 3.2 showed what it must not touch, the host's own children and attributes.
- Lines 14 and 15 keep a reference to each part that changes: the tea's name and the seconds.
- Line 18 takes the new state, an object with
teaandleft. - Line 20 skips any value that matches what the card showed last time. Line 21 writes the others. Line 22 says which one it wrote.
- Line 24 remembers what the card shows now.
Line 30 prints Wrote tea and Wrote left. Line 31 prints only Wrote left. Line 32 prints nothing, because nothing changed. The result shows Oolong: 29 s.
<span>. The note box is never touched.Why check a value that's the same? Setting textContent always swaps in a new text node, even with the same text. A MutationObserver sees that as a change. Lesson 5.5 showed a component whose own writes woke its observer, and "only write new text" was one way out. And lesson 5.1 guarded attributeChangedCallback() the same way. The browser calls it even when an attribute gets the value it already has.
Libraries like Lit do this for you
Writing references and checks by hand gets long. Lit, the library in stage 8, writes them for you. Here is the same card in Lit, to read:
import { LitElement, html } from "lit";
class TeaBrew extends LitElement {
static properties = { tea: {}, left: { type: Number } };
render() {
return html`<p><b>${this.tea}</b>: ${this.left} s</p>
<input aria-label="Tasting note">`;
}
}
customElements.define("tea-brew", TeaBrew);Line 7 looks like one HTML string with two values in it. It isn't. The html tag gets the fixed pieces of text and the values apart. Lit's docs say it "parses and creates static HTML once, and then only updates changed values". Its source shows how:
- It joins the fixed pieces into one
<template>, with a marker where each value goes. A marker in text looks like<?lit$123456789$>, which the parser turns into a comment node (lines 349 and 356). - It keeps that template under the pieces' array, so each
htmlliteral is parsed once (line 688). - Each element gets one clone of it (line 1223).
- On each render, it compares every value with the last one it wrote, and skips it if they match (lines 1475 and 1476). A changed text goes into the same text node (line 1577).
Lit also puts a string value in as text. To render a string as HTML, you ask for it with its unsafeHTML() directive. Stage 7 builds a renderer like this by hand.
How do you update a list without losing focus?
One value is easy: keep its element. A list is harder, because rows come, go, and change places. And each row can hold its own state, like a number typed in a box. In this playground, the tea list sorts itself by cups as you type. Click Black tea's box, and type 5:
<ul id="menu"></ul><template id="tea-row"> <li><label><span></span> <input type="number" min="0"></label></li></template> <script> const teas = [ { id: "green", name: "Green tea", cups: 0 }, { id: "oolong", name: "Oolong", cups: 0 }, { id: "black", name: "Black tea", cups: 0 }, ]; const menu = document.querySelector("#menu"); const template = document.querySelector("#tea-row"); function makeRow(tea) { const row = template.content.firstElementChild.cloneNode(true); row.dataset.id = tea.id; row.querySelector("span").textContent = tea.name; return row; } menu.addEventListener("input", (event) => { const id = event.target.closest("li").dataset.id; teas.find((tea) => tea.id === id).cups = Number(event.target.value); teas.sort((a, b) => b.cups - a.cups); render(); }); function render() { menu.replaceChildren(...teas.map(makeRow)); } render();</script>Black tea moves to the top, because the data says it has 5 cups. But replaceChildren() swapped in three fresh rows, so every box is empty and nothing has focus. Type another digit, and it goes nowhere.
- New rows every time puts Black tea first, but every box is empty, and nothing has focus.
- Reuse rows by position keeps the three rows and changes only their names. Your 5 stays in the third row, which now says Oolong.
- By key, with moveBefore() moves Black tea's own row to the top. Your 5 and your cursor go with it.
Reusing rows by position is the trap. Lit's docs warn about the same thing with checkboxes. Reorder the list, and the names move to new rows, but the ticks stay where they were.
The fix is a key: a value that names each item for good, like a tea's id. Here is how the last version draws the list:
- Line 29 makes a
Mapthat keeps each tea's row under its id. - Line 33 makes a row only for a tea it hasn't seen before.
- Line 35 finds the row in that place now. Line 36 stops if it's already the right one.
- Line 37 moves the row into place with
moveBefore(). Line 38 usesinsertBefore()for a new row, or in a browser withoutmoveBefore().
A full version has a third step: remove the rows whose tea is gone. The practical example below does all three.
Three friends share a table at Leaf and Kettle, each with a half-full cup. They swap seats to sit by the window. A careful waiter carries each cup to its owner's new seat. A careless one leaves the cups where they were, and Asha ends up with Ravi's tea.
- In real life: Each friend
- In JavaScript: Each tea in the data
- In real life: Their name
- In JavaScript: The key,
tea.id - In real life: Their half-full cup
- In JavaScript: The row, with the number typed in it
- In real life: Carrying each cup to its owner's new seat
- In JavaScript: Moving the row with
moveBefore() - In real life: Leaving the cups where they were
- In JavaScript: Reusing rows by position
Why does the insertBefore() version lose the cursor? It takes the row out of the page and puts it back in. Taking out an element that has focus drops the focus. moveBefore() moves the row without taking it out, so the focus stays, as lesson 3.5 showed. Safari doesn't have moveBefore(), so it takes line 38. The playground's By key, with insertBefore() choice shows what that does: the number stays, the cursor doesn't.
Lit's repeat() does this for you: give it a key for each item, and it moves each item's DOM with the item. Stage 15 builds a keyed list from scratch.
Is innerHTML safe inside a shadow root?
No. That's Ravi's second worry. A component that puts a review in with innerHTML runs whatever markup the review holds. Lesson 7.2 showed one image with an onerror attribute. Here are five tricks, in one review card:
<tea-review></tea-review> <script src="tea-review.js"></script>The parser makes a real <script> element, but a script that arrives through innerHTML is marked as already started. Nothing prints. It's the only one of the five that stays quiet.
- <script> is the only quiet one. The HTML Standard marks a script that arrives through
innerHTMLas already started, so it never runs. Lesson 7.1 met this rule. - <img onerror> runs as soon as the image fails to load.
- <svg onload> runs as soon as the svg is in the page.
- <details ontoggle> runs as the details box opens, with no click at all.
- <iframe srcdoc> holds a whole page, and its script writes into the frame. A
srcdocframe shares the origin of the page around it. So on your site, that script could reach your page throughparent.
One more trick doesn't even need markup that runs by itself: a link whose address starts with javascript:. It runs its code when someone clicks it.
So stopping scripts protects nothing. MDN's page on shadowRoot.innerHTML says it stops <script> but is "susceptible to many other ways" to run code. And a shadow root is no wall: code in it runs in your page, as lesson 6.3 showed.
Can escaping make innerHTML safe?
Escaping swaps each special character for a code that the parser shows as text, like < for <. The JavaScript path's XSS lesson covers it. It fixes text and quoted attributes. It can't fix an address:
<div id="card"></div> <script> function escape(text) { return text.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`); } const tea = { name: "<b>Oolong</b>", page: "javascript:console.log('The link ran code')" }; const root = document.querySelector("#card").attachShadow({ mode: "open" }); root.innerHTML = `<a href="${escape(tea.page)}">${escape(tea.name)}</a>`; console.log(root.querySelector("b")); console.log(root.querySelector("a").getAttribute("href"));</script>- Lines 4 to 6 are the helper. It swaps each of the five special characters for its number code.
- Line 8 is the data: a name with tags, and an address that starts with
javascript:. - Line 10 escapes both and puts them into the markup.
- Line 11 prints
null. The name stayed text, so there's no<b>element. - Line 12 prints the link's address:
javascript:console.log('The link ran code'). It's exactly what went in.
Escaping only changes how the characters are written. The browser reads ' back as ', so the address is the same as before. On your site, a click on that link would run its code.
Why it matters: for text, don't build a string at all. Use textContent and setAttribute(), as lesson 7.2 did. For markup you can't avoid, use the next section's tool.
How does setHTML() make HTML from users safe?
Some data really is HTML. A review with bold words should show them in bold. For this, Chrome and Firefox have setHTML(), on elements and on shadow roots. It parses the string like innerHTML, but cleans it as it parses. The HTML Standard says the markup is "sanitized as it is parsed", and "unsafe content is removed".
Parcels for the shop's staff go through the post room first. The post room opens each one. It passes on letters and books, and takes out anything that could start a fire, whatever the label says. Ravi gets his post without wondering what's inside.
- In real life: The post room
- In JavaScript:
setHTML() - In real life: A parcel
- In JavaScript: The HTML string
- In real life: Letters and books
- In JavaScript: Safe markup, like
<b>and<p> - In real life: Anything that could start a fire
- In JavaScript:
<script>,<iframe>, and everyonattribute - In real life: Whatever the label says
- In JavaScript: Even if your own list allows them
Here is the review card with setHTML(). The component is in the tea-review.js tab:
<tea-review></tea-review> <script src="tea-review.js"></script>- Lines 1 to 4 of
tea-review.jsare the review: bold text with a class, an image withonerror, and a link with ajavascript:address. - Line 13 puts it into the shadow root with
setHTML()instead ofinnerHTML. - Line 14 prints what the shadow root holds:
<p>Asha says: <b>Lovely</b> oolong! <a>Read more</a></p>.
Nothing prints The review ran code, and clicking Read more does nothing.
setHTML() keeps the bold text but drops its class. The image goes, with its onerror. The link stays, without its javascript: address, so clicking it does nothing.With no settings, setHTML() uses the standard's built-in safe default: a short list of what may stay. MDN lists what's always removed, even if your own list allows it: <script>, <iframe>, <object>, <embed>, and every on attribute. The default is strict in other ways too. It has no class, id, style, or data- attributes. In Chrome, it also drops <img>, <button>, and <input>.
So setHTML() is for HTML you didn't write. Your component's own markup, with its classes and styles, still belongs in a template. Safari doesn't have setHTML(). Check for it with "setHTML" in ShadowRoot.prototype, and fall back to textContent, as exercise 6 does. One warning about older articles: Chrome 105 to 118 had a different Sanitizer API, built to an older spec. Its methods don't match today's.
What do setHTMLUnsafe() and parseHTMLUnsafe() do?
setHTML() has a twin, setHTMLUnsafe(). Unsafe means it removes nothing, unless you pass it a sanitizer. MDN says it "should almost never be used" when setHTML() is there. Like innerHTML, it never runs the scripts it inserts, but handlers still run. Why does it exist? One reason is shadow roots written in HTML:
<div id="first"></div><div id="second"></div> <script> const markup = `<tea-note><template shadowrootmode="open"><p>Fresh today</p></template></tea-note>`; const first = document.querySelector("#first"); const second = document.querySelector("#second"); first.innerHTML = markup; second.setHTMLUnsafe(markup); console.log(first.querySelector("tea-note").shadowRoot); console.log(second.querySelector("tea-note").shadowRoot.innerHTML);</script>- Line 5 is markup with a
<template shadowrootmode="open">, a shadow root written in HTML. Stage 9 teaches these. - Line 8 sets it with
innerHTML. Line 9 sets it withsetHTMLUnsafe(). - Line 10 prints
null.innerHTMLleft a plain template, so the note has no shadow root. - Line 11 prints
<p>Fresh today</p>.setHTMLUnsafe()built the shadow root.
Chrome's DevTools console also warns about line 8, and suggests setHTMLUnsafe() or parseHTMLUnsafe(). Document.parseHTMLUnsafe(html) does the same for a whole page: it returns a new document. The standard says its scripts don't run. Nothing else in it runs while it sits there either. But move its nodes into your page, and an <img onerror> among them runs. Both methods have been Baseline since September 2025.
Trusted Types
"Never pass data to innerHTML" is an easy rule to forget. Trusted Types makes the browser enforce it. A page turns it on with a Content Security Policy rule, require-trusted-types-for 'script'. Then innerHTML, setHTMLUnsafe(), and the other HTML sinks refuse plain strings. They only take TrustedHTML values, made by a policy you write. The XSS lesson builds one. Here is a blocked assignment:
<meta http-equiv="Content-Security-Policy" content="require-trusted-types-for 'script'"><div id="card"></div> <script> const review = "<b>Lovely</b> oolong"; const root = document.querySelector("#card").attachShadow({ mode: "open" }); try { root.innerHTML = review; } catch (error) { console.log(error.message); } root.setHTML(review); console.log(root.innerHTML);</script>- Line 1 turns Trusted Types on for this page.
- Line 8 sets
innerHTMLto a plain string. Line 10 prints the error:Failed to set the 'innerHTML' property on 'ShadowRoot': This document requires 'TrustedHTML' assignment. - Line 12 sets the same string with
setHTML(). Line 13 prints<b>Lovely</b> oolong.setHTML()cleans every string itself, so Trusted Types lets it through.
At Ravi's bank, the clerk only takes forms with the manager's stamp. A form without one goes back, however neat it looks. The stamp shows that someone checked the form first.
- In real life: The clerk
- In JavaScript:
innerHTML, with Trusted Types on - In real life: The manager's stamp
- In JavaScript: A
TrustedHTMLvalue from your policy - In real life: A form without a stamp
- In JavaScript: A plain string, which throws a TypeError
- In real life: Checking the form before stamping it
- In JavaScript: The policy cleaning the HTML
One thing to know for components: a template made with template.innerHTML = …, like the kit's card, also throws on such a page. Lit makes its own policy, called lit-html, for the markup you write in its templates (line 263 of lit-html.ts). Trusted Types has been Baseline since February 2026.
Read each row across: what you call, whether it removes unsafe markup, whether it builds declarative shadow roots, and whether Trusted Types guards it.
| What you call | Does it remove unsafe markup? | Does it build declarative shadow roots? | Does Trusted Types guard it? |
|---|---|---|---|
innerHTML | No. Handlers, javascript: addresses, and frames all stay. | No. A <template shadowrootmode> stays a plain template. | Yes. With Trusted Types on, a plain string throws. |
setHTMLUnsafe() | No, unless you pass it a sanitizer. | Yes. The template becomes a real shadow root. | Yes. With Trusted Types on, a plain string throws. |
setHTML() | Yes, always. It removes unsafe markup even if your own list allows it. | Only if your list allows <template> and shadowrootmode. The default list drops them. | No. It cleans every string, so it needs no policy. |
Put together, these are safe defaults for a component:
- Text from data goes in with
textContent. - Attributes go in with
setAttribute()or a property. Addresses are checked first. - Your own markup lives in a template, cloned once.
- HTML from users goes through
setHTML(), withtextContentas the fallback. - Data never goes into an
innerHTMLstring.
Which way should a web component render?
Most components use more than one way. The markup is cloned once, and the values in it are updated by hand. Read each row across: what the component shows, what to render it with, what each update costs, and whether it's safe with data from users.
| What the component shows | Render it with | What does each update cost? | Is it safe with data from users? |
|---|---|---|---|
| Markup you wrote, the same in every copy, like a card's box and styles. | A template, cloned once per element. | One parse, when the module loads. Each element copies nodes that are already built. | Yes. The markup is yours, and data goes in afterwards as text. |
| A few values that change, like a countdown or a price. | Saved references, written only when a value differs. | One write per value that changed. Nothing else is touched. | Yes, with textContent and safe attributes. |
| A list whose rows hold their own state, like typed text or focus. | Rows kept under a key, and moved with moveBefore(). | One move for each row whose place changed, and one new row for each new item. | Yes, the same way. |
| HTML from users, like a review with bold text. | setHTML(), or textContent where the browser lacks it. | A parse and a clean-up on every call. | Yes. Unsafe markup is removed. |
| A quick sketch with no data and nothing to keep. | innerHTML. | A full parse and a whole new set of nodes on every update. | No. Never put data into the string. |
Why isn't the third way built into the browser? It has been proposed. DOM Parts, a proposal for marking the parts of a template that change, was last updated in 2023. In 2025, Justin Fagnani proposed a templating API. He points out that no standard API makes DOM from data safely and then updates it efficiently. Until one does, libraries like Lit fill the gap.
- A card's box, heading, and styles, the same in every card
- A countdown that changes every second
- A price that changes at noon
- A menu where each row has a Cups box, sorted by cups
- An order list that customers drag into a new order
- A customer's review that may hold bold text
- A tea description from a content editor, with links and lists
Sort each part of the tea shop by the way it should render.
Updating the tea menu by key
Now the kit. Lesson 7.2's menu made one tea-card per tea. At noon, the kitchen sends a new list: Oolong costs 6, Black tea is sold out, and Chai is new. Here is a render() that handles all of it with the kit's cards:
<div id="menu"></div><button>Noon prices</button> <script type="module"> import "./tea-kit/index.js"; const menu = document.querySelector("#menu"); const cards = new Map(); function render(teas) { teas.forEach((tea, index) => { if (!cards.has(tea.id)) cards.set(tea.id, document.createElement("tea-card")); const card = cards.get(tea.id); card.setAttribute("name", tea.name); card.setAttribute("price", tea.price); const here = menu.children[index] ?? null; if (card === here) return; if (card.isConnected && menu.moveBefore) menu.moveBefore(card, here); else menu.insertBefore(card, here); }); for (const [id, card] of cards) { if (teas.some((tea) => tea.id === id)) continue; card.remove(); cards.delete(id); } } render([ { id: "green", name: "Green tea", price: 4 }, { id: "oolong", name: "Oolong", price: 5 }, { id: "black", name: "Black tea", price: 3 }, ]); document.querySelector("button").addEventListener("click", () => { render([ { id: "oolong", name: "Oolong", price: 6 }, { id: "green", name: "Green tea", price: 4 }, { id: "chai", name: "Chai", price: 5 }, ]); });</script>- Line 8 makes the
Mapthat keeps each card under its tea's id. - Line 12 makes a card only for a tea it hasn't seen. Lines 14 and 15 set its name and price.
- Lines 16 to 19 move the card into place:
moveBefore()where it can,insertBefore()for a new card. - Lines 21 to 25 are the third step. A card whose tea isn't in the new list is removed, and forgotten.
- Lines 28 to 32 draw the first menu. Lines 35 to 39 draw the noon menu when you press the button.
Press Noon prices. Oolong's card moves to the top and shows Price: 6. Green tea's card moves down. Chai's card is new, and Black tea's card is gone. The Oolong and Green tea cards are the same elements as before.
One more change makes this cheaper. Lines 14 and 15 set both attributes on every card, every time. The browser calls the card's attributeChangedCallback() even when a value is the same, and lesson 7.1's card wrote its text again. So the kit's card gets one new line:
attributeChangedCallback(name, oldValue, newValue) {
if (oldValue === newValue) return;
const text = newValue ?? "";
if (name === "name") this.shadowRoot.getElementById("name").textContent = text;
if (name === "price") this.shadowRoot.getElementById("price").textContent = `Price: ${text}`;
}Line 2 is new. If the attribute already had this value, the card does nothing. Now, pressing Noon prices leaves Green tea's shadow root alone. Lesson 7.1's card rewrote its heading and its price there for nothing. Oolong's card changes only its price line. What every card shows stays exactly as before.
Common mix-ups
- "innerHTML is safe inside a shadow root." No. Handlers,
javascript:addresses, andsrcdocframes run there too. A shadow root isn't a security boundary. - "innerHTML doesn't run scripts, so it's safe." No. It skips
<script>, but four of the playground's five tricks still ran. - "Escaping makes any value safe in HTML." No. An escaped
javascript:address is the same address, and it still runs. - "setHTMLUnsafe() is a safer innerHTML." No. It removes nothing unless you pass it a sanitizer. Its one extra power is building declarative shadow roots.
- "Articles about the Sanitizer API from 2022 still apply." No. Chrome 105 to 118 had a different API. Use today's
setHTML()docs. - "Cloning a template on every update keeps the typing." No. Each clone is a new set of nodes, with empty boxes.
- "A row's position works as its key." No. When the list is sorted, state stays at the position and ends up next to the wrong item.
- "A component may never render in its constructor." No. Filling its own shadow root there is fine. Only the host's own children and attributes are off limits.
Practice exercises
Answer first, then use the hints. Each result runs live, so you can check yourself.
Lines 6 and 8 set exactly the same markup. What does the console print?
<div id="card"></div> <script> const root = document.querySelector("#card").attachShadow({ mode: "open" }); const markup = `<p>Oolong</p><input aria-label="Tasting note">`; root.innerHTML = markup; const box = root.querySelector("input"); root.innerHTML = markup; console.log(box === root.querySelector("input"));</script>false. Line 8 sets the same string again, but innerHTML doesn't compare. It removes the old box and builds a new one, so box points at an element that left the page.
What does the console print?
<div id="card"></div> <script> const root = document.querySelector("#card").attachShadow({ mode: "open" }); root.setHTML(`<b class="star" onclick="console.log('Clicked')">Lovely</b>`); console.log(root.innerHTML);</script><b>Lovely</b>. Bold text is allowed, so the <b> stays. onclick is always removed, and the default list doesn't include class.
Right now, the tick prints false. Change render() so the box survives. After your change, what does the console print?
<tea-brew></tea-brew> <script> const template = document.createElement("template"); template.innerHTML = `<p>Oolong: <span></span> s</p><input aria-label="Tasting note">`; class TeaBrew extends HTMLElement { left = 3; constructor() { super(); this.attachShadow({ mode: "open" }); } connectedCallback() { this.render(); const box = this.shadowRoot.querySelector("input"); setTimeout(() => { this.left -= 1; this.render(); console.log(box === this.shadowRoot.querySelector("input")); }, 1000); } // Change render(): clone the template once, then set only the seconds. render() { this.shadowRoot.innerHTML = `<p>Oolong: ${this.left} s</p><input aria-label="Tasting note">`; } } customElements.define("tea-brew", TeaBrew);</script><tea-brew></tea-brew> <script> const template = document.createElement("template"); template.innerHTML = `<p>Oolong: <span></span> s</p><input aria-label="Tasting note">`; class TeaBrew extends HTMLElement { left = 3; constructor() { super(); this.attachShadow({ mode: "open" }); } connectedCallback() { this.render(); const box = this.shadowRoot.querySelector("input"); setTimeout(() => { this.left -= 1; this.render(); console.log(box === this.shadowRoot.querySelector("input")); }, 1000); } render() { if (!this.seconds) { this.shadowRoot.append(template.content.cloneNode(true)); this.seconds = this.shadowRoot.querySelector("span"); } this.seconds.textContent = this.left; } } customElements.define("tea-brew", TeaBrew);</script>true. The first render clones the template once and keeps the <span>. The tick only sets its text, so the box is never replaced.
Before you fix it, what does the console print? Then fix it without an HTML string.
<div id="card"></div> <script> const name = "Asha's blend"; const root = document.querySelector("#card").attachShadow({ mode: "open" }); root.innerHTML = `<h3 title='${name}'>${name}</h3>`; console.log(root.querySelector("h3").title);</script><div id="card"></div> <script> const name = "Asha's blend"; const root = document.querySelector("#card").attachShadow({ mode: "open" }); const heading = document.createElement("h3"); heading.title = name; heading.textContent = name; root.append(heading); console.log(root.querySelector("h3").title);</script>Asha. The apostrophe in the name ends the single-quoted attribute early. The fix never builds a string: it sets title and textContent as properties, so the title is Asha's blend.
The second render leaves Black tea's row behind, so the console prints 3. Add the third step. After your fix, what does the console print?
<ul id="menu"></ul> <script> const menu = document.querySelector("#menu"); const rows = new Map(); function render(teas) { teas.forEach((tea, index) => { if (!rows.has(tea.id)) rows.set(tea.id, document.createElement("li")); const row = rows.get(tea.id); row.textContent = tea.name; const here = menu.children[index] ?? null; if (row !== here) menu.insertBefore(row, here); }); // Remove the rows whose tea is gone. } render([ { id: "green", name: "Green tea" }, { id: "oolong", name: "Oolong" }, { id: "black", name: "Black tea" }, ]); render([ { id: "oolong", name: "Oolong" }, { id: "green", name: "Green tea" }, ]); console.log(menu.children.length);</script><ul id="menu"></ul> <script> const menu = document.querySelector("#menu"); const rows = new Map(); function render(teas) { teas.forEach((tea, index) => { if (!rows.has(tea.id)) rows.set(tea.id, document.createElement("li")); const row = rows.get(tea.id); row.textContent = tea.name; const here = menu.children[index] ?? null; if (row !== here) menu.insertBefore(row, here); }); for (const [id, row] of rows) { if (teas.some((tea) => tea.id === id)) continue; row.remove(); rows.delete(id); } } render([ { id: "green", name: "Green tea" }, { id: "oolong", name: "Oolong" }, { id: "black", name: "Black tea" }, ]); render([ { id: "oolong", name: "Oolong" }, { id: "green", name: "Green tea" }, ]); console.log(menu.children.length);</script>2. The second render has no Black tea, so its row is removed from the page and from the map. Oolong and Green tea keep their rows.
The review runs code. Make the card use setHTML() where it can, and textContent where it can't. After your fix, what does the console print?
<tea-review></tea-review> <script> const review = `<b>Lovely</b> oolong! <img src="x" onerror="console.log('The review ran code')">`; class TeaReview extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); } connectedCallback() { this.shadowRoot.innerHTML = `<p>Asha says: ${review}</p>`; console.log(this.shadowRoot.querySelectorAll("img").length); } } customElements.define("tea-review", TeaReview);</script><tea-review></tea-review> <script> const review = `<b>Lovely</b> oolong! <img src="x" onerror="console.log('The review ran code')">`; class TeaReview extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); } connectedCallback() { const html = `<p>Asha says: ${review}</p>`; if ("setHTML" in ShadowRoot.prototype) this.shadowRoot.setHTML(html); else this.shadowRoot.textContent = `Asha says: ${review}`; console.log(this.shadowRoot.querySelectorAll("img").length); } } customElements.define("tea-review", TeaReview);</script>0. setHTML() keeps the bold text and drops the image with its onerror. A browser without it shows the review as text, which has no elements at all.
Check your understanding
For each question, ask two things: which nodes are new, and where the data ends up.
Question 1 of 8In this redraw code, what does line 16 print?
Read the code, then predict<div id="card"></div> <script> const root = document.querySelector("#card").attachShadow({ mode: "open" }); function render(left) { root.innerHTML = `<p>Oolong: ${left} s</p> <input aria-label="Tasting note"> <button>Done</button>`; } render(30); const box = root.querySelector("input"); box.value = "Floral"; root.querySelector("button").addEventListener("click", () => console.log("Done!")); render(29); console.log(box === root.querySelector("input")); console.log(box.isConnected); console.log(root.querySelector("input").value.length); root.querySelector("button").click(); </script>Choose an answer to see the explanation.
Question 2 of 8A component puts a review into its shadow root with
innerHTML. Which review runs code before anyone clicks?Choose an answer to see the explanation.
Question 3 of 8A list reuses its rows by position. You type 5 in Black tea's box, and the list sorts Black tea to the top. Where is your 5?
Choose an answer to see the explanation.
Question 4 of 8What does
setHTML()keep of<b class="star" onclick="…">Lovely</b>, with its default settings?Choose an answer to see the explanation.
Question 5 of 8What does Unsafe mean in the name
setHTMLUnsafe()?Choose an answer to see the explanation.
Question 6 of 8A page sends
require-trusted-types-for 'script'. Which line still accepts a plain string?Choose an answer to see the explanation.
Question 7 of 8Why does
moveBefore()keep the focus wheninsertBefore()loses it?Choose an answer to see the explanation.
Question 8 of 8In this compare-before-write code, what does the third call, on line 32, print?
Read the code, then predict<tea-brew></tea-brew> <script> const template = document.createElement("template"); template.innerHTML = `<p><b></b>: <span></span> s</p><input aria-label="Tasting note">`; class TeaBrew extends HTMLElement { #parts = {}; #shown = {}; constructor() { super(); this.attachShadow({ mode: "open" }).append(template.content.cloneNode(true)); this.#parts.tea = this.shadowRoot.querySelector("b"); this.#parts.left = this.shadowRoot.querySelector("span"); } render(state) { for (const key of ["tea", "left"]) { if (state[key] === this.#shown[key]) continue; this.#parts[key].textContent = state[key]; console.log(`Wrote ${key}`); } this.#shown = { ...state }; } } customElements.define("tea-brew", TeaBrew); const brew = document.querySelector("tea-brew"); brew.render({ tea: "Oolong", left: 30 }); brew.render({ tea: "Oolong", left: 29 }); brew.render({ tea: "Oolong", left: 29 }); </script>Choose an answer to see the explanation.
Key takeaways
innerHTMLparses its string and replaces every node, on every update. Typed text, focus, selection, scrolling, and listeners go with the old nodes.- A template saves the parsing. Cloning a fresh copy on every update still replaces every node.
- To update only what changed, keep references to the parts that change, and write a value only when it differs.
- In a list, keep each row under a key and move it with
moveBefore(). Rows reused by position leave their state next to the wrong item. innerHTMLruns handlers,javascript:addresses, andsrcdocframes, in a shadow root too. Only<script>stays quiet.- Use
textContentfor text andsetHTML()for HTML from users.setHTMLUnsafe()removes nothing. Trusted Types makes the browser refuse plain strings.
Remember the one-liner.
Clone your markup once, update only what changed, and let data in only as text or through setHTML().
Sources
The facts on this page come from these standards, docs, and posts:
- ShadowRoot: innerHTML property, MDN.
- Let's learn how modern JavaScript frameworks work by building one, Nolan Lawson.
- template-clone-demo, the benchmark behind that post, Nolan Lawson.
- HTMLTemplateElement: content property, MDN.
- Shadow DOM, Templates & Slots, Modern Web Guidance, Chrome for Developers.
- Rendering: When templates render, Lit.
- lit-html.ts, at lit-html 3.3.3, Lit.
- Built-in directives: unsafeHTML, Lit.
- Lists: When to use map or repeat, Lit.
- Element: moveBefore() method, MDN.
- HTML Standard: The script element's already started flag, WHATWG.
- ShadowRoot: setHTML() method, MDN.
- HTML Standard: DOM parsing and serialization APIs, WHATWG.
- HTML Standard: The built-in safe default configuration, WHATWG.
- Element: setHTMLUnsafe() method, MDN.
- Trusted Types API, MDN.
- CSP: require-trusted-types-for, MDN.
- The time is right for a DOM templating API, Justin Fagnani.
- DOM Parts proposal, WICG.
- HTML Standard: Requirements for custom element constructors and reactions, WHATWG.
Coming next: Placing content with slots, the first lesson of the next module in Shadow DOM, templates, and slots. A slot shows the page's own content inside your shadow root, exactly where you want it.