List items often share the same markup even when their text differs. The HTML template element lets you define that markup once and create a separate list item for each value.

The browser keeps the template's contents in a document fragment outside the rendered page. JavaScript can copy the fragment through the template's content property, leaving the original available for the next item.

Keep IDs on the template and the destination list. An ID inside the template would be copied with each item, giving several elements on the page the same ID.

Steps to use the HTML template element:

  1. Create shopping-list.html from the starter markup in a new test folder using your text editor.
    shopping-list.html
    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Shopping list</title>
    </head>
    <body>
      <h1>Shopping list</h1>
      <ul id="shopping-list"></ul>
    </body>
    </html>
  2. Insert the item template immediately after </ul> in shopping-list.html.
      <template id="shopping-item">
        <li>Item name</li>
      </template>

    Item name is placeholder text for each fresh copy.

  3. Insert the script immediately after </template> in shopping-list.html.
      <script>
        const list = document.querySelector("#shopping-list");
        const template = document.querySelector("#shopping-item");
        const items = ["Oat milk", "Brown rice"];
     
        for (const name of items) {
          const copy = template.content.cloneNode(true);
          copy.querySelector("li").textContent = name;
          list.append(copy);
        }
      </script>

    cloneNode(true) copies the fragment and its list item. textContent sets the label as plain text, and append() moves the copied item from the fragment into the list. The script sits below both elements so the browser has already parsed them when the selectors run.

  4. Save shopping-list.html.
  5. Open shopping-list.html from its local file address in desktop Chrome with JavaScript enabled.

    The picture shows file:///home/user/site/shopping-list.html. Your file address uses the folder where you saved the page.

  6. Verify that Shopping list contains exactly Oat milk and Brown rice in that order.

    A blank list or a visible Item name means the check failed.

Share this guide