AI Hints
Home›JavaScript Tutorial›Changing the Page
JavaScript · Lesson 95 of 138

Creating Elements

Adding to the page.

⏱ 2 min read▶ Video at 1:54:17🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Pages often need new content. A new message in a chat, a new row in a table, a new item in a list. Create element makes a new element, and append puts it on the page.

Creating Elements
From the video: Creating Elements
  • New messages, rows, items
  • createElement
  • append

Building a list from data

We start with an array of fruit and an empty list. For each fruit, create element makes a new list item. We set its text, and append adds it to the list. Finally, we add a paragraph with the total. Every item on the page came from the array.

index.htmlpython
<link rel="stylesheet" href="style.css">
<h1>Fruit</h1>
<ul id="list"></ul>
<script>
  const fruit = ["Apple", "Banana", "Cherry", "Mango"];
  const list = document.querySelector("#list");

  for (const name of fruit) {
    const li = document.createElement("li");
    li.textContent = name;
    list.append(li);
  }

  const total = document.createElement("p");
  total.textContent = `${fruit.length} kinds of fruit`;
  document.body.append(total);
</script>
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#f7df1e;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}

Adding and removing

Append adds at the end, and prepend adds at the start. Remove takes an element off the page. And replace children swaps out everything inside an element at once, which is handy for redrawing a whole list from your data.

keyvalue
createElement('li')make an element
append / prependadd to the end / start
el.remove()take it away
replaceChildren()redraw everything

Summary

Create element makes new elements, append adds them, and remove takes them away. Next, making pages respond to clicks, with events.

Key takeaways
  • createElement
  • append / prepend
  • remove
Next up: Events — responding to clicks