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:
- Create
shopping-list.htmlfrom the starter markup in a new test folder using your text editor. - Insert the script immediately after
</template>inshopping-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.textContentsets the label as plain text, andappend()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. - Save
shopping-list.html. - Open
shopping-list.htmlfrom 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.
- 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.