completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Filling a template with data

Fill an HTML template with data in JavaScript: find the blanks in each copy, set text safely with textContent, and render a list from an array.

By the end, you can
  • 01
    Fill a copy of a templateFind each blank in a copy before you add it to the page, fill it, and keep a reference for later changes.
  • 02
    Keep data as dataPut text in with textContent and attributes with setAttribute(), and spot the attributes that run code.
  • 03
    Render a list from an arrayMake one copy per item, add them all in one change, and update rows instead of drawing them again.

How do you fill an HTML template with data?

Every morning, Leaf and Kettle's kitchen sends the day's teas to the menu page. They arrive as data: a name and a price for each tea. Ravi already has a row template from lesson 7.1. Each copy of it is a row with empty spots.

"So how do I get Green tea and 4 into a copy?" Ravi asks. Asha has a second question. "Customers name their own blends. What if a name has odd characters in it?"

To fill an HTML template with data, clone its content and find each empty spot in the copy with querySelector(). Set each spot's text with textContent, then append the copy to the page. Do it once per item to build a list.

Here is one row, filled with one tea:

Filling one copy of a row templatePop out in the code editor (opens in a new tab)HTML
<template id="tea-row">  <li><span class="name"></span>: <span class="price"></span></li></template><ul id="menu"></ul> <script>  const tea = { name: "Green tea", price: 4 };  const template = document.querySelector("#tea-row");   const copy = template.content.cloneNode(true);  copy.querySelector(".name").textContent = tea.name;  copy.querySelector(".price").textContent = tea.price;  document.querySelector("#menu").append(copy);</script>
ResultLoading…
  • Lines 1 to 3 are the template. Its row has two empty spots: a span with the class name, and one with the class price.
  • Line 4 is the empty list that rows go into.
  • Line 7 is the data: one tea, as a JavaScript object.
  • Line 10 makes a copy of the template's content, as lesson 7.1 did.
  • Line 11 finds the name spot in the copy and puts the tea's name in it. Line 12 does the same for the price.
  • Line 13 adds the filled copy to the list.

The result shows Green tea: 4. The template itself is still blank, so the next copy starts empty too.

A window called template holds a blank card that reads ___: ___, with the note stays blank. An arrow labelled clone leads down to a window called copy, whose card reads Green tea: 4, with the note filled with textContent. An arrow labelled append leads from the copy to a window called page, which shows Green tea: 4.template___: ___stays blankclonecopyGreen tea: 4filled with textContentappendpageGreen tea: 4
Line 10 clones the template. Lines 11 and 12 fill the blanks in the copy with textContent. Line 13 adds the filled copy to the page. The template stays blank, ready for the next copy.
Real-life analogyA template is a pad of order slips

Leaf and Kettle takes orders on a pad of printed slips. Each slip has two boxes, Tea and Price. A waiter tears off a fresh slip, writes in the boxes, and pins it on the kitchen board. The pad stays full of blank slips.

In real life: The pad of printed slips
In JavaScript: The <template>
In real life: Tearing off a fresh slip
In JavaScript: template.content.cloneNode(true)
In real life: The boxes printed on each slip
In JavaScript: The empty spots, found with querySelector()
In real life: Writing in a box
In JavaScript: Setting textContent
In real life: Pinning the slip on the kitchen board
In JavaScript: append() adds the copy to the page
The main idea

Fill the copy, never the template. Clone the content, find the empty spots, and put text in with textContent. Then add the copy to the page. Every copy starts blank, so each one can hold a different tea.

You met append() and textContent in Creating & changing elements, on the JavaScript path. This lesson answers Ravi and Asha in order. How do you find the spots? What is safe to put in them? How do you fill a whole list? And where should the template live?

How do you find the places to fill in a template copy?

A copy is a DocumentFragment, a light holder for nodes. It has querySelector(), querySelectorAll(), and getElementById(), like the page does. So you search a copy the way you search a small page. First, though, the template has to mark its empty spots, so your code can find them.

Ways to mark the empty spots

There are four common markers. Each one has its own job.

  • A class, like class="name". The first example used classes. But classes are for CSS too. Rename one for a new style, and the filling code finds nothing.
  • A data attribute, like data-field="name". Attributes whose names start with data- are free for your own use. The browser gives them no job of its own, so a style change won't touch them.
  • A part attribute, like part="name". It lets the page style an element inside a shadow root, which stage 4 teaches. A search can find it, but then one attribute has two jobs.
  • An id, like id="name". It works inside a shadow root. In the page, it causes trouble, as you'll see below.

A data-field marker can also say which piece of data goes where. Then one loop fills every spot:

Filling every data-field spot with one loopPop out in the code editor (opens in a new tab)HTML
<template id="tea-row">  <li><span data-field="name"></span>: <span data-field="price"></span></li></template><ul id="menu"></ul> <script>  const tea = { name: "Oolong", price: 5 };  const copy = document.querySelector("#tea-row").content.cloneNode(true);  for (const blank of copy.querySelectorAll("[data-field]")) {    blank.textContent = tea[blank.dataset.field];  }  document.querySelector("#menu").append(copy);</script>
ResultLoading…
  • Line 2 marks two spots: data-field="name" and data-field="price".
  • Line 9 finds every element in the copy that has a data-field attribute.
  • Line 10 reads each spot's marker with blank.dataset.field. The dataset property gives you an element's data- attributes, without the data- part. So it reads name, then price, and puts tea.name and tea.price into the spots.

The result shows Oolong: 5. Why it matters: add a new spot to the template, and the same loop fills it. The code doesn't change.

Why do ids cause trouble in a row template?

An id must be unique in its tree. But a row template is copied many times into the same list. Watch what happens to an id:

Three copies of a row with an idPop out in the code editor (opens in a new tab)HTML
<template id="tea-row">  <li id="name"></li></template><ul id="menu"></ul> <script>  const template = document.querySelector("#tea-row");  for (const name of ["Green tea", "Oolong", "Black tea"]) {    const copy = template.content.cloneNode(true);    copy.getElementById("name").textContent = name;    document.querySelector("#menu").append(copy);  }  console.log(document.querySelectorAll("#name").length);  console.log(document.getElementById("name").textContent);</script>
ResultLoading…
  • Line 2 gives the row the id name.
  • Lines 8 to 12 make three copies. Line 10 fills each one through the copy's own getElementById(). That works, because each copy is searched on its own.
  • Line 13 prints 3: three elements in the page now share the id name.
  • Line 14 prints Green tea. document.getElementById() returns only the first one.

The list looks fine, so the bug is easy to miss. Anything that points at the id, like a <label for>, finds only the first row. Inside a shadow root, ids are safe again. Each card has its own root and its own set of ids, as lesson 6.3 showed. That's why the kit's tea card can find its spots with this.shadowRoot.getElementById().

Fill the copy before you append it

Order matters too. This playground runs the same three lines in three orders: find the spot, fill it, and append the copy. Try each one:

Playground: when do you fill the copy?
Find, fill, and append, in three ordersPop out in the code editor (opens in a new tab)HTML
<template id="tea-row">  <li class="name"></li></template><ul id="menu"></ul> <script>  const menu = document.querySelector("#menu");  const copy = document.querySelector("#tea-row").content.cloneNode(true);  const name = copy.querySelector(".name");  name.textContent = "Green tea";  menu.append(copy);  console.log(copy.childNodes.length);</script>
ResultLoading…
Try it yourself
Filled before it joins the page

Line 9 finds the blank in the copy. Line 10 fills it. Line 11 moves the filled row into the list. Line 12 prints 0: the copy is empty now.

Only lines 9 to 11 change: the same three lines, in a different order. Line 12 prints how many nodes the copy still holds.
  • Fill, then append works. Line 12 prints 0: after line 11, the copy is empty.
  • Append, then search fails. Line 9 moves the row into the list first. So line 10 searches an empty copy and gets null. Line 11 throws TypeError: Cannot set properties of null (setting 'textContent').
  • Find, append, then fill works. Line 9 keeps the spot in name before the copy empties.

The DOM Standard explains the empty copy. When you insert a fragment, the browser moves its children out. The fragment stays behind, with nothing in it. Lesson 7.1 saw the same thing with template.content.

Two halves. Before append: a tag called name points at a card that reads <li class="name"> inside a crate called copy. After append: the crate called copy is empty, and the tag called name points at a card that reads Green tea inside a window called page.name<li class="name">copybefore append()pageGreen teacopyemptynameafter append()
Before append(), the copy holds the row, and name points at its <li>. After it, the copy is empty and the row is in the page. name still points at the same <li>, so line 11 can fill it.

A variable like name holds a reference: a way to reach one element. It doesn't matter where the element moves. It's like remembering which hook you hung your coat on. Why it matters: search a copy before you append it. To change a row later, keep the reference you found, and set its text whenever the data changes.

What is the difference between textContent and innerHTML?

Now Asha's question. Regulars at Leaf and Kettle can name their own blends, and the menu shows those names. One regular typed a name with tags in it. The playground puts that name into a row in three ways:

Playground: textContent, innerHTML, or innerText?
A tea name with tags, put into a row three waysPop out in the code editor (opens in a new tab)HTML
<template id="tea-row">  <li class="name"></li></template><ul id="menu"></ul> <script>  const name = `Green <b>tea</b><img src="x" onerror="console.log('This name ran code')">`;  const copy = document.querySelector("#tea-row").content.cloneNode(true);  copy.querySelector(".name").textContent = name;  document.querySelector("#menu").append(copy);</script>
ResultLoading…
Try it yourself
Every character stays text

The row shows the whole name, tags and all. textContent puts the string into one text node, and the browser never reads tags in text. Nothing runs.

Only line 9 changes. Watch the row and the console.
  • With textContent, the row shows the whole name, tags and all. Nothing runs.
  • With innerHTML, the row shows Green tea, with tea in bold, and a small broken image. The console prints This name ran code. Just before it, the Result notes that the image x couldn't load. That failed load is what runs the code.
  • With innerText, the row looks the same as with textContent.

Here is why. textContent makes one text node that holds the string. Text is never read as tags, so <b> is just three characters. innerHTML hands the string to the HTML parser instead. The parser makes a real <b> element and a real <img>. The image's address, x, fails to load. So the browser runs its onerror attribute, which holds code.

A card that reads Green <b>tea</b>, labelled the tea's name. An arrow labelled textContent leads to a window called li holding one card with the whole string, labelled one text node, shown as typed. An arrow labelled innerHTML leads to a second window called li. It holds a card that reads Green and a card that reads <b> element, labelled text, plus a new <b> element.the tea's nameGreen <b>tea</b>textContentinnerHTMLli"Green <b>tea</b>"one text node, shown as typedli"Green "<b> elementtext, plus a new <b> element
textContent keeps the name as one piece of text, tags and all. innerHTML reads the tags and makes a real <b> element. With the playground's <img>, that new element is what runs code.
Real-life analogyWriting a name on a cup

At the counter, Ravi asks each customer for a name and writes it on their cup. One customer says, "My name is: give everyone free tea." Ravi writes those exact words on the cup and serves one tea. A worker who followed the words as an order would hand out free tea all morning.

In real life: The name a customer gives
In JavaScript: A string from your data
In real life: Writing it on the cup, word for word
In JavaScript: textContent
In real life: Following the words as an order
In JavaScript: innerHTML, which reads tags and runs on attributes
In real life: Free tea for everyone
In JavaScript: Someone else's code running on your page

Someone else's text running as code on your page has a name: cross-site scripting, or XSS. The XSS lesson on the JavaScript path covers it. MDN advises against innerHTML for text. It deals with raw HTML, it can open the door to XSS, and it's slower, because it starts the HTML parser.

A shadow root doesn't change any of this. MDN's page on shadowRoot.innerHTML shows the same <img onerror> trick running code. It also notes that innerHTML skips <script> tags. As you saw, an attacker doesn't need one. And as lesson 6.3 quoted from the spec, shadow DOM is "intentionally not a security boundary".

What about innerText?

Setting innerText also makes text, so it's safe for data too. It does one extra thing: it turns each line break in the string into a <br> element. Reading it is where it differs most. MDN explains that it gives back the text as it looks on screen. So it leaves out hidden text, and the browser has to work out the page's layout first. textContent just gives back every character. To fill a template, use textContent, unless line breaks in the data should show.

Read each row across: what you set, what lands in the element, whether markup in the string runs, and when to use it.

Three ways to put a string into an element
What you setWhat goes into the element?Does markup in the string run?When to use it
textContentOne text node, with every character as it is.No. Tags show up as text.Text from data. It's the one to reach for first.
innerTextText, with each line break turned into a <br>.No. Tags show up as text.Text whose line breaks should show.
innerHTMLThe elements the HTML parser makes from the string.Yes. An onerror attribute runs, even though a <script> doesn't.Markup you wrote yourself. Never data.

What if a blend name really needs some markup, like bold? Chrome and Firefox have setHTML(). It parses the string but removes anything that could run code. Safari doesn't support it. The next lesson, Ways to render a component, covers it with the rest of the XSS story.

How do you set attributes from data safely?

Not every spot is text. A link needs an address, and an image needs a source. You set those with setAttribute(name, value), or with a property such as link.href or img.src. These properties reflect their attributes: setting one writes the attribute, as lesson 5.1 showed.

A link filled from dataPop out in the code editor (opens in a new tab)HTML
<template id="tea-row">  <li><a></a></li></template><ul id="menu"></ul> <script>  const tea = { name: `Asha's "<b>bold</b>" blend`, page: "/teas/asha" };  const copy = document.querySelector("#tea-row").content.cloneNode(true);  const link = copy.querySelector("a");  link.textContent = tea.name;  link.href = tea.page;  link.setAttribute("title", tea.name);  document.querySelector("#menu").append(copy);  console.log(document.querySelectorAll("b").length);</script>
ResultLoading…
  • Line 7 is a blend whose name holds quotes and a <b> tag.
  • Line 10 sets the link's text with textContent.
  • Line 11 sets its address through the href property.
  • Line 12 sets its title, the tip a mouse shows, with setAttribute().
  • Line 14 prints 0: there's no <b> element anywhere in the page.

Hover over the link in the result. The tip shows the name exactly as typed, quotes and all. An attribute's value is stored as text. It can't break out of its quotes or turn into tags, the way a string glued into HTML can. That's why MDN calls attributes like name safe: their values are never run or parsed as HTML.

Which attributes run code?

Some attributes don't hold plain text. The browser runs them, or goes where they point. In this playground, one string from the data goes into three different attributes:

Playground: which attribute gets the string?
One string from the data, set as three attributesPop out in the code editor (opens in a new tab)HTML
<template id="tea-row">  <li><a>Oolong</a></li></template><ul id="menu"></ul> <script>  const page = "javascript:console.log('This tea ran code')";  const copy = document.querySelector("#tea-row").content.cloneNode(true);  const link = copy.querySelector("a");  link.setAttribute("title", page);  document.querySelector("#menu").append(copy);  console.log(link.outerHTML);</script>
ResultLoading…
Try it yourself
A title is only text

Line 12 shows the string in the link's title, the small tip a mouse shows. The browser only ever shows a title, so hovering over Oolong shows the string, and nothing runs.

Only the attribute's name on line 10 changes. Line 12 prints the link, so you can see where the string went.

In all three, line 12 shows the string exactly as it came. What differs is what the browser does with it. A title is only ever shown. An onclick runs when someone clicks. And an href is an address: one that starts with javascript: runs its code when a page follows the link. MDN's security notes list the attributes to watch:

  • Every on attribute, like onclick or onerror. Its value is JavaScript.
  • Addresses the browser goes to, like href on a link, action on a form, or src on an iframe. MDN explains that an address starting with javascript: runs its code when the browser follows it.
  • srcdoc on an iframe. Its value is a whole HTML page.
  • src on a script. It loads code from wherever it points.

So never put data into an on attribute, and never let data pick an attribute's name. For an address, build it yourself. Or use it only if it starts with https://, /, or #. Exercise 6 adds that check. Why it matters: textContent keeps text safe, but attributes need this second look. The next lesson goes further, with tools that check every value for you.

How do you render a list from an array with a template?

The kitchen doesn't send one tea. It sends an array. To render a list, repeat the same steps for each item: clone, fill, and collect. MDN's template example fills table rows the same way.

A menu from an array of teasPop out in the code editor (opens in a new tab)HTML
<template id="tea-row">  <li><span data-field="name"></span>: <span data-field="price"></span></li></template><ul id="menu"></ul> <script>  const teas = [    { name: "Green tea", price: 4 },    { name: "Oolong", price: 5 },    { name: "Black tea", price: 3 },  ];  const template = document.querySelector("#tea-row");  const rows = new DocumentFragment();   for (const tea of teas) {    const copy = template.content.cloneNode(true);    for (const blank of copy.querySelectorAll("[data-field]")) {      blank.textContent = tea[blank.dataset.field];    }    rows.append(copy);  }  document.querySelector("#menu").append(rows);</script>
ResultLoading…
  • Lines 7 to 11 are the data: three teas.
  • Line 13 makes an empty DocumentFragment called rows. It's a holder that isn't in the page.
  • Lines 15 to 21 run once per tea. Line 16 clones the template. Lines 17 to 19 fill its data-field spots, as before. Line 20 moves the filled row into rows.
  • Line 22 adds all three rows to the menu at once.

The result shows three rows: Green tea: 4, Oolong: 5, and Black tea: 3.

One change or three?

Why collect the rows first? Appending each row straight into the menu works too. The difference is how many changes the page goes through. A MutationObserver can count them. It reports each change to an element's children as one record, as lesson 5.5 showed:

Playground: one change or three?
Three rows, and an observer that counts the changesPop out in the code editor (opens in a new tab)HTML
<ul id="menu">  <li>Yesterday's teas</li></ul><template id="tea-row"><li></li></template> <script>  const menu = document.querySelector("#menu");  const template = document.querySelector("#tea-row");  new MutationObserver((records) => {    console.log("Change records:", records.length);  }).observe(menu, { childList: true });   const rows = new DocumentFragment();  for (const name of ["Green tea", "Oolong", "Black tea"]) {    const copy = template.content.cloneNode(true);    copy.querySelector("li").textContent = name;    menu.append(copy);  } </script>
ResultLoading…
Try it yourself
Three changes

Line 17 adds each row to the list as soon as it's filled. That's three changes to the page, so the observer gets three records. Yesterday's row stays at the top.

Only lines 17 and 19 change. Lines 9 to 11 print how many change records the observer gets.
  • Append each row prints Change records: 3. Each row was its own change.
  • Collect in a fragment prints Change records: 1. Line 19 moved all three rows in one change.
  • replaceChildren() also prints Change records: 1. Yesterday's row is gone, and the three new rows are in.

The observer's callback runs once in every case, after the script finishes. What changes is the number of records in its list. The DOM Standard spells this out: inserting a fragment queues one record for all of its children together.

Real-life analogyCarrying cups on a tray

A table orders three teas. Ravi could walk to the table three times, with one cup each trip. Or he could put all three cups on a tray and walk once. The table gets three cups either way. With the tray, the people at the table see one delivery, not three.

In real life: The tray
In JavaScript: A DocumentFragment
In real life: Putting a cup on the tray
In JavaScript: rows.append(copy)
In real life: One trip to the table
In JavaScript: One menu.append(rows)
In real life: The table seeing one delivery
In JavaScript: The observer getting one record
Two halves. On the left, three cards, Green tea, Oolong and Black tea, each have their own arrow into a crate called menu, with the note append each row: 3 records. On the right, the same three cards sit in a crate called rows. One arrow leads from it into a crate called menu, with the note append the fragment: 1 record.Green teaOolongBlack teamenuappend each row: 3 recordsGreen teaOolongBlack tearowsmenuappend the fragment: 1 record
On the left, each row goes into the menu on its own: three changes, three records. On the right, the rows wait in a fragment first, and one append() moves all three: one change, one record.

Is a fragment faster? Not by much. MDN says its speed benefit "is often overstated". In some browsers, a loop of appends is even a little faster. So choose a fragment because the list changes once, and code that watches it sees one change. Otherwise, write whichever reads more clearly.

replaceChildren() is the simple way to draw a list again. It takes away every old child and adds the new ones in one step. The DOM Standard queues one record for the whole swap. Call it with nothing inside the brackets, and it empties the element.

Should you redraw a list or update its rows?

Prices at Leaf and Kettle change during the day. The easy fix is to draw the whole list again, with fresh copies, each time. But a row can hold more than text. This row has a box where a customer types how many cups they want. Its price changes every two seconds:

Playground: a new row, or the same row?
A price that changes every two secondsPop out in the code editor (opens in a new tab)HTML
<template id="tea-row">  <li>Green tea, <span class="price"></span> <input aria-label="Cups" size="3"></li></template><ul id="menu"></ul> <script>  const template = document.querySelector("#tea-row");  const menu = document.querySelector("#menu");  let price = 4;   function draw() {    const copy = template.content.cloneNode(true);    const priceText = copy.querySelector(".price");    priceText.textContent = price;    menu.replaceChildren(copy);  }   draw();  setInterval(() => {    price += 1;    draw();  }, 2000);</script>
ResultLoading…
Try it yourself
Every redraw throws your typing away

Each draw() clones a fresh row, and line 15 swaps it in. The old row goes, with the box you were typing in. The new box is empty, and nothing has focus.

Only lines 11 to 15 change. Click in the Cups box, type a number, and wait for the price to change.

Click in the Cups box and type a number. With Draw a new row, the price goes up within two seconds, and your number is gone. The cursor has left the box too. With Fill the same row, the price still changes. But your number and your cursor stay.

Why? Your typing and your cursor belong to one <input> element. A fresh copy of the template brings a fresh, empty box. Line 15's replaceChildren() removes the old box, and the focus leaves with it. In the second version, lines 11 to 13 make the row once. After that, draw() only changes the price text, through the saved reference. Nolan Lawson points out the same cost of drawing everything again: it resets state such as the value of an input.

Real-life analogyNew tables or new price cards

Leaf and Kettle changes its prices at noon. The staff could carry out every table and bring in new ones. A customer halfway through writing an order would lose the order pad. Or the staff could swap only the small price card on each table. Then everyone keeps their seat and their pad.

In real life: Bringing in new tables
In JavaScript: Drawing new rows from fresh template copies
In real life: A customer's half-written order
In JavaScript: The text and the cursor in an <input>
In real life: Swapping only the price card
In JavaScript: Setting textContent on a saved reference
In real life: The same table, with a new card
In JavaScript: The same row element, with new data

In a list, the same idea needs a way to find each tea's row again. Keep each row's references under the tea's id. That id is called a key. When new data comes in, look up the row by its key and fill it. Only a tea you haven't seen before gets a new copy. The practical example below keeps its cards in a Map this way. The next lesson builds the full version, which also handles teas that are removed or moved.

Should a component's template be in the HTML or in JavaScript?

So far, the templates sat in the page. A component can use one from the page too. MDN's guide finds its template with document.getElementById() in the constructor. Lesson 7.1's kit card made its template at the top of its module instead. Does the choice matter? Try a small tea-special component in three places:

Playground: where is the template?
Today's special, with its template in three placesPop out in the code editor (opens in a new tab)HTML
<template id="special">  <p>Today's special: <strong></strong></p></template><tea-special name="Oolong"></tea-special> <script src="tea-special.js"></script>
ResultLoading…
Try it yourself
It works on this page

The template and the tag are both in the page. Line 4 of tea-special.js finds the template by its id, and the result shows Today's special: Oolong.

The first two choices load the same tea-special.js, which looks for the template by id. The third changes the tea-special.js tab: it makes its own template.
  • Template in the page works. Line 4 of tea-special.js finds the template by its id. The result shows Today's special: Oolong.
  • Both in a shadow root fails. The shop's shadow root holds the template and the special. document.getElementById() searches the page's own tree only, so line 4 gets null. Line 6 throws TypeError: Cannot read properties of null (reading 'content').
  • Template in the module works anywhere. This tea-special.js makes its template on lines 1 and 2, so there's nothing to search for.

The second choice is lesson 6.3's rule again: each shadow root keeps its own ids, and the page's search never looks inside. A template in the page has two more problems. Its id is shared by the whole page, so two components that both pick id="row" clash. And every page that uses the component must include the template too.

Real-life analogyA recipe on the wall, or in the cook's notebook

Leaf and Kettle's kitchen has a recipe pinned on the wall. Anyone in that kitchen can read it or fix a typo. But when the cook helps out at the other branch, the recipe isn't on that wall. A recipe in the cook's own notebook goes wherever the cook goes.

In real life: The recipe pinned on the kitchen wall
In JavaScript: A <template id> in the page's HTML
In real life: Anyone in that kitchen can fix a typo
In JavaScript: Anyone who edits the page's HTML can change it
In real life: The other branch's bare wall
In JavaScript: Another page, or a shadow root, without the template
In real life: The cook's own notebook
In JavaScript: A template made in the component's module

A template in the page still has its place. People who edit HTML but not JavaScript can change it, and the browser parses it with the page. For markup that only one page uses, that's a fine choice. For a component that many pages use, keep the template in its module.

A tag that builds each template once

Writing createElement("template") and innerHTML for every template gets long. Libraries use a tagged template literal instead. That's a template literal with a function name in front, like html`<p>Fresh today</p>`. JavaScript calls the function with the literal's pieces of text. The Template literals lesson covers tags. Here is a small html tag:

Three notes built from one tagged templatePop out in the code editor (opens in a new tab)HTML
<tea-note></tea-note><tea-note></tea-note><tea-note></tea-note> <script type="module" src="tea-note.js"></script>
ResultLoading…
  • The page, lines 1 to 3, has three notes. Line 5 loads tea-note.js, the second tab.
  • In tea-note.js, line 1 makes a WeakMap, a map whose keys are objects. It will hold one template per literal.
  • Lines 3 to 11 are the tag. It gets strings, the array of the literal's pieces of text.
  • The first time it meets a literal, lines 5 to 8 build a template from it and save it. Line 5 prints Building a template.
  • Line 10 returns a fresh clone, every time.
  • Line 17 uses the tag in the constructor, so it runs once per note.

The console prints Building a template only once, and all three notes show Fresh today. That works because of a rule of tagged templates. MDN says the tag is called with "the exact same literal array, no matter how many times the literal is evaluated". So the array makes a good key. Lit, the library in stage 8, keeps its templates under this array too. This small tag takes plain markup only: it ignores ${…} values. Data still goes in after cloning, with textContent.

Markup in its own file

Some teams want the markup in a real .html file. A text module imports a file's contents as one string:

Importing a template's markup as textJavaScript
import markup from "./tea-note.html" with { type: "text" };

const template = document.createElement("template");
template.innerHTML = markup;

Line 1 imports tea-note.html as a string called markup. Lines 3 and 4 turn it into a template, once, when the module loads. MDN notes that the file can hold any text, and that the server's content type is ignored. Text modules are new: the box below shows the first versions that have them. Until your visitors' browsers do, keep the markup in the module.

Read each row across: where the template lives, what's good about it, and what to watch for.

Where a component's template can live
Where the template livesWhat's good about it?What should you watch for?
A <template id> in the page's HTMLAnyone who edits the page's HTML can change it. The browser parses it with the page.Every page must include it. Its id is shared by the whole page, and document.getElementById() can't find it inside a shadow root.
A template made at the top of the component's moduleIt travels with the component, so it works on any page and in any shadow root.People who only edit HTML files won't find the markup there.
An html tag with a cacheEach template literal is turned into a template once, even inside code that runs many times.The tag takes plain markup only. Data still goes in after cloning, with textContent.
A text module, with { type: "text" }The markup lives in its own .html file, next to the component.Only the newest browsers can import text modules.

Building the tea menu from data

Now everything together, with the kit. The menu page gets its teas as data and makes one kit tea-card per tea. Ravi's card from lesson 7.1 stays exactly as it was.

The tea menu, made from an arrayPop out in the code editor (opens in a new tab)HTML
<ul id="menu"></ul><button>Oolong costs 6 now</button> <template id="tea-row">  <li><tea-card></tea-card></li></template> <script type="module">  import "./tea-kit/index.js";   const teas = [    { id: "green", name: "Green tea", price: 4 },    { id: "oolong", name: "Oolong", price: 5 },    { id: "asha", name: "Asha's <b>bold</b> blend", price: 6 },  ];  const template = document.querySelector("#tea-row");  const cards = new Map();  const rows = new DocumentFragment();   for (const tea of teas) {    const copy = template.content.cloneNode(true);    const card = copy.querySelector("tea-card");    card.setAttribute("name", tea.name);    card.setAttribute("price", tea.price);    cards.set(tea.id, card);    rows.append(copy);  }  document.querySelector("#menu").replaceChildren(rows);   document.querySelector("button").addEventListener("click", () => {    cards.get("oolong").setAttribute("price", 6);  });</script>
ResultLoading…
  • Lines 4 to 6 are the row template: a list item that holds one card.
  • Lines 11 to 15 are the data. Line 14 is a blend whose name holds a <b> tag.
  • Line 17 makes a Map that keeps each card under its tea's id, its key. Line 18 makes the fragment.
  • Lines 20 to 27 run once per tea. Line 22 finds the card in the copy. Lines 23 and 24 give it a name and a price, as attributes. Line 25 saves the card under its key. Line 26 moves the row into the fragment.
  • Line 28 swaps the three rows into the menu, in one change.
  • Lines 30 to 32 run when you press the button. Line 31 finds Oolong's card by its key and sets one attribute.

The menu shows three cards. Press Oolong costs 6 now: only Oolong's card changes, to Price: 6. Nothing is drawn again.

Now look at Asha's blend. Its card shows Asha's <b>bold</b> blend, tags and all. The page set an attribute, and the card writes its attributes with textContent, as it has since lesson 6.1. So the name stays text from start to end.

One more detail. These cards come from cloneNode(), so they aren't upgraded until line 28 adds them to the page. Setting attributes before that is fine: the card reads them as it upgrades. Properties set before an upgrade need care, as lesson 4.2 showed.

Common mix-ups

  • "textContent removes the tags from a string." No. It keeps every character. The tags show up as text, as the playground showed.
  • "innerHTML is safe because it doesn't run script tags." No. It skips <script>, but an image's onerror attribute still runs. MDN shows this for shadowRoot.innerHTML.
  • "A shadow root makes innerHTML safe." No. Code that runs in a shadow root runs in your page. Shadow DOM is not a security boundary.
  • "You can fill the copy after you append it." No. Appending empties the copy, so a search finds nothing. Find the spots first, and keep the references.
  • "setAttribute() is always safe." No. on attributes are code, javascript: addresses run, and srcdoc is a whole page.
  • "A DocumentFragment makes the page much faster." No. MDN calls that benefit overstated. A fragment gives you one change instead of many.
  • "Ids in a row template are fine." No. Each copy repeats the id, so the page ends up with duplicates. Use a data-field marker, or keep ids inside a shadow root.

Practice exercises

Answer first, then use the hints. Each result runs live, so you can check yourself.

Exercise 1 · Warm-upTags in a tea name

What does the console print?

<template id="tea-row"><li class="name"></li></template><ul id="menu"></ul> <script>  const copy = document.querySelector("#tea-row").content.cloneNode(true);  const name = copy.querySelector(".name");  name.textContent = "<i>Oolong</i>";  document.querySelector("#menu").append(copy);  console.log(name.querySelector("i"));</script>
ResultLoading…

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upCount the changes

    The observer prints how many records it gets. What does the console print?

    <template id="tea-row"><li></li></template><ul id="menu"></ul> <script>  const menu = document.querySelector("#menu");  const template = document.querySelector("#tea-row");  new MutationObserver((records) => console.log(records.length)).observe(menu, { childList: true });   for (const name of ["Green tea", "Oolong", "Black tea"]) {    const copy = template.content.cloneNode(true);    copy.querySelector("li").textContent = name;    menu.append(copy);  }</script>
    ResultLoading…

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeOne change for the whole list

      Change the loop so the menu changes only once. After your change, what does the console print?

      <template id="tea-row"><li></li></template><ul id="menu"></ul> <script>  const menu = document.querySelector("#menu");  const template = document.querySelector("#tea-row");  new MutationObserver((records) => console.log(records.length)).observe(menu, { childList: true });   // Change the loop so the menu changes only once.  for (const name of ["Green tea", "Oolong", "Black tea"]) {    const copy = template.content.cloneNode(true);    copy.querySelector("li").textContent = name;    menu.append(copy);  }</script>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeFind the bug in the HTML string list

        This list is built the way many components do it, by adding HTML strings. Before you fix it, what does the console print? Then fix it with a template.

        <ul id="menu"></ul> <script>  const teas = ["Green tea", "Oolong", `<img src="x" onerror="console.log('Ran code')">`];  const menu = document.querySelector("#menu");  for (const name of teas) {    menu.innerHTML += `<li>${name}</li>`;  }</script>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeChange one price without a redraw

          Make the button change only Oolong's price to 6, without drawing the menu again. After the click, what does Oolong's row show?

          <template id="tea-row">  <li><span class="name"></span>: <span class="price"></span></li></template><ul id="menu"></ul><button>Oolong costs 6 now</button> <script>  const teas = [    { id: "green", name: "Green tea", price: 4 },    { id: "oolong", name: "Oolong", price: 5 },  ];  const template = document.querySelector("#tea-row");  const menu = document.querySelector("#menu");  for (const tea of teas) {    const copy = template.content.cloneNode(true);    copy.querySelector(".name").textContent = tea.name;    copy.querySelector(".price").textContent = tea.price;    menu.append(copy);  }   document.querySelector("button").addEventListener("click", () => {    // Change only Oolong's price to 6, without drawing the menu again.  });</script>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeMake the tea links safe

            The tea links get their addresses from the data. Before the fix, which tea's link would run code when a page follows it? Then make it safe.

            <template id="tea-row">  <li><a></a></li></template><ul id="menu"></ul> <script>  const teas = [    { name: "Green tea", page: "/teas/green" },    { name: "Oolong", page: "javascript:console.log('This link ran code')" },  ];  const template = document.querySelector("#tea-row");  for (const tea of teas) {    const copy = template.content.cloneNode(true);    const link = copy.querySelector("a");    link.textContent = tea.name;    link.href = tea.page;    document.querySelector("#menu").append(copy);    console.log(tea.name, link.getAttribute("href"));  }</script>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, think about where the data ends up: as text, as markup, or as an attribute.

              The filling a template quiz · 7 questionsScore: first tries count
              1. Question 1 of 7In this fill-then-append code, what does line 12 print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <template id="tea-row">
                  <li class="name"></li>
                </template>
                <ul id="menu"></ul>
                
                <script>
                  const menu = document.querySelector("#menu");
                  const copy = document.querySelector("#tea-row").content.cloneNode(true);
                  const name = copy.querySelector(".name");
                  name.textContent = "Green tea";
                  menu.append(copy);
                  console.log(copy.childNodes.length);
                </script>

                Choose an answer to see the explanation.

              2. Question 2 of 7A tea's name is <b>Oolong</b>. You set it with textContent. What does the row show?

                Choose an answer to see the explanation.

              3. Question 3 of 7innerHTML doesn't run <script> tags. So why did the tea name in the playground run code?

                Choose an answer to see the explanation.

              4. Question 4 of 7Which attribute is safe to fill with text a customer typed?

                Choose an answer to see the explanation.

              5. Question 5 of 7With this fragment code, what does line 10 print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <ul id="menu">
                  <li>Yesterday's teas</li>
                </ul>
                <template id="tea-row"><li></li></template>
                
                <script>
                  const menu = document.querySelector("#menu");
                  const template = document.querySelector("#tea-row");
                  new MutationObserver((records) => {
                    console.log("Change records:", records.length);
                  }).observe(menu, { childList: true });
                
                  const rows = new DocumentFragment();
                  for (const name of ["Green tea", "Oolong", "Black tea"]) {
                    const copy = template.content.cloneNode(true);
                    copy.querySelector("li").textContent = name;
                    rows.append(copy);
                  }
                  menu.append(rows);
                </script>

                Choose an answer to see the explanation.

              6. Question 6 of 7A list is drawn again from fresh template copies every two seconds. Why does the Cups box lose what you typed?

                Choose an answer to see the explanation.

              7. Question 7 of 7Why can't document.getElementById() find a template inside a shadow root?

                Choose an answer to see the explanation.

              Key takeaways

              • To fill a template, clone its content, find each spot in the copy, fill it, and append the copy. The template stays blank.
              • Mark spots with data-field attributes or classes. Ids repeat when a row is copied into the page, but they're fine inside a shadow root.
              • Search the copy before you append it. Afterwards, it's empty. Keep references to the spots you'll change later.
              • Put text in with textContent. innerHTML parses tags and can run code from the data, in a shadow root too.
              • Attributes and properties store text. But on attributes, javascript: addresses, and srcdoc run code, so check addresses before you use them.
              • For a list, collect the copies in a DocumentFragment and add them in one change, or use replaceChildren(). Update existing rows by key instead of redrawing, so focus and typing stay.
              • A component's template belongs in its module, where it works on any page and in any shadow root.

              Remember the one-liner.
              A template gives you blank copies. Fill each copy with textContent and safe attributes, then add it to the page, so data never becomes HTML.

              Sources

              The facts on this page come from these standards and docs:

              Coming next: Ways to render a component, the next lesson in Shadow DOM, templates, and slots. Compare HTML strings, cloning, and updating only what changed, and see the full story of keeping data out of HTML.

              CompleteFrontend Clear concepts. Working examples.