Skip to content
dreamcode
dreamcode
Map
Creating elements
Lesson 37 of 48
+15 XP on finish
JS WEB APISChapter 7 · JS Web APIs

Creating Elements

document.createElement("li") makes a new element that is not on the page yet. Set its text and classes, then attach it with parent.append(element). Remove one with element.remove(). Turning an array of data into elements, one per item, is one of the most common jobs in front-end code.

Worked example

How it reads

  • createElement makes the element in memory only
  • append is what puts it on the page
  • children.length counts the elements inside the list
Cloud tip: Build all the elements first and append them in one go when you have hundreds of items; it keeps the page fast.
index.js
JAVASCRIPT
real JavaScript, runs in the live page below
preview · index.htmllive page, click around after you run
Console
Run your code to see its output here.
YOUR TURN

With a loop, add one li for each name in ["Altair", "Rigel", "Spica"], give the second new one the class glow, then log how many items the list has: 4.

Press Run to check your work.