← Web basics: HTML, CSS and JavaScript
Creating elements
Build new parts of the page with createElement and append.
JavaScript can add brand-new elements to a page. It takes three steps: make the element with document.createElement("li"), fill it in (for example set its textContent or add a class), and attach it somewhere with parent.append(newElement). Until you append it, the element exists only in memory and is not on the page. To take an element away, call element.remove().
<ul id="shopping"></ul>
<script>
const list = document.querySelector("#shopping");
const items = ["Eggs", "Rice", "Tomatoes"];
for (const item of items) {
const li = document.createElement("li");
li.textContent = item;
list.append(li);
}
</script>For each item in the array, a new li is created, given its text, and appended to the list. The page ends up with three list items that were never written in the HTML.
Building elements from data (an array) is how real apps show messages, products or search results that change all the time.
Setting textContent is safe for text a visitor typed. Avoid pasting visitor text into innerHTML, which could turn it into real tags.