JavaScript in the page · Lesson 30 of 45
Creating elements
Build part of the page with code, from data.
8 minutes2 games
document.createElement("li") creates a new element in memory; parent.append(el) puts it on the page; el.remove() takes it away. This is how any list is built from data: products, messages, comments.
HTML
<ul id="list"></ul>
<button id="add">Add course</button>
<script>
const courses = ["HTML", "CSS", "JavaScript"]
const list = document.querySelector("#list")
function render() {
list.replaceChildren()
for (const name of courses) {
const li = document.createElement("li")
li.textContent = name
const del = document.createElement("button")
del.textContent = "✕"
del.onclick = () => {
courses.splice(courses.indexOf(name), 1)
render()
}
li.append(" ", del)
list.append(li)
}
}
document.querySelector("#add").onclick = () => {
courses.push("Course " + (courses.length + 1))
render()
}
render()
</script>Click “Add course” and ✕. The idea: data lives in an array, and render redraws it each time.
Order the lines
Order the lines to add a new item to the list.
- Click the lines in the right order
Quick question
Which line removes el from the page?
Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.