A to-do list: you type "Buy rice", press Enter, and a new item appears at the bottom of the list. Click the item, and it is crossed out. A page like this can't be written completely in HTML from the start, because its items only exist once the user types them.
In the earlier DOM lesson you mostly changed elements that were already there. In this lesson you learn four things: making new elements from JavaScript, removing them, managing their classes, and attaching one listener for many elements at once. These four things are the base of any list that can grow, like a to-do list or a chat window.
Making a new element with createElement and appendChild
The HTML is only an empty <ul id="list"></ul>. This code adds one item to it:
const list = document.querySelector('#list')
const li = document.createElement('li')
li.textContent = 'Learn the DOM'
list.appendChild(li)
document.querySelector('#list')finds the element withid="list". The hash sign#means id.document.createElement('li')makes a new<li>. So far the element is only in memory. It is not on the page yet.li.textContent = 'Learn the DOM'sets its text.list.appendChild(li)putsliinsidelist, as its last child. Only now doesliappear on the page.
The page now holds <ul id="list"><li>Learn the DOM</li></ul>. list.append(li) is allowed too, and does the same.
Each appendChild adds at the very bottom, so the element that goes in first is shown at the top. Need several items? Repeat those three steps (make it, set its text, put it in), for example with a loop:
for (let i = 1; i <= 2; i++) {
const li = document.createElement('li')
li.textContent = 'Task ' + i
list.appendChild(li)
}
The result is two new items: Task 1 then Task 2. Each round has to make a new li, because one element can only be in one place.
Removing an element
Find the element, then call remove():
const item = document.querySelector('#remove-me')
item.remove()
The older way, which you will still see often: item.parentNode.removeChild(item). It means "parent, please remove this child".
Managing classes with classList
CSS usually uses classes to change how things look, for example to cross out a finished item. classList manages classes one at a time (el is any element):
el.classList.add('done')adds the classdone.el.classList.remove('done')removes that class.el.classList.toggle('done')adds the class when it isn't there, and removes it when it is.el.classList.contains('done')answerstrueorfalse: the class is there or not.
classList.add does not touch the other classes on the element. That is different from el.className = 'done', which overwrites all of them.
One listener for every item: event delegation
A click on an <li> doesn't stop at that <li>. The click travels up to its parent, the <ul>, and keeps going up. So one listener on the <ul> is enough to catch clicks on every <li>:
list.addEventListener('click', (e) => {
if (e.target.tagName === 'LI') {
e.target.classList.add('done')
}
})
- The listener is attached once, to
list, not to each<li>. eis the information about that click.e.targetis the element that was actually clicked.e.target.tagName === 'LI'makes sure the clicked element really is an<li>, not an empty gap in the<ul>.tagNameis the element's tag name, always in capital letters.e.target.classList.add('done')marks only the item that was clicked.
The listener's body only runs when there is a click, so before any click no item is marked. Attaching one listener to the parent for all its children is called event delegation. You see how it differs from a listener on each <li> when a new item is added. With a listener on each <li>, the new item doesn't react to a click, because it didn't exist yet when the listeners were attached. With delegation, the new item reacts right away, because the listener is on the <ul>.
When an <li> holds other tags. For example <li><span>Buy milk</span> <button>Delete</button></li>. A click on the text makes e.target the <span>, so e.target.tagName === 'LI' is false and nothing is marked. Use closest:
list.addEventListener('click', (e) => {
const li = e.target.closest('li')
if (li) {
li.classList.add('done')
}
})
e.target.closest('li') checks the clicked element, then goes up through its parents one by one until it finds an <li>. If there is none, it gives null, and if (li) skips the code inside. One more thing: unlike e.target, e.currentTarget is always the element the listener is attached to, here list.
⚠️ Items that never appear, or all get crossed out
- Forgetting
appendChild. An element fromcreateElementwon't appear until you put it inside a parent. classList.addoutside the listener. That code runs as soon as the page opens, so the item is marked before anyone clicks. PutclassList.addinside the listener's callback.- Marking
listinstead ofe.target.list.classList.add(...)marks the whole list. The clicked element is ine.target. innerHTMLfor text from users. If the text contains tags, the browser treats those tags as HTML. UsetextContent.
🔬 Try it yourself
Paste a piece of HTML into the tool below and see its structure as a tree: parents, children and siblings. A click follows this tree when it travels up from an <li> to the <ul>.
TL;DR: document.createElement('li') makes a new element, textContent sets its text, and parent.appendChild(li) shows it as the parent's last child. el.remove() removes the element el. classList.add, remove, toggle and contains manage an element's classes one at a time. Event delegation means attaching one listener to the parent, not to each child. A click on a child travels up to the parent, and e.target tells you which child was clicked, including children added later.
⚡ Make a new item from JavaScript
Write:
const list = document.querySelector('#list')
const li = document.createElement('li')
li.textContent = 'Learn the DOM'
list.appendChild(li)
Meaning: list is an empty <ul> on the page. createElement makes an <li> element that is only in memory. The element appears on the page after appendChild, as the last child of list. Need two items? Make another new li, because one element can only be in one place.
⚡ Manage classes one at a time
Write:
el.classList.add('done')
el.classList.toggle('done')
Meaning: el is an element, and classList manages its classes. add adds a class, remove removes it, and toggle adds it when it isn't there and removes it when it is. classList does not touch the other classes. That is different from el.className = 'done', which overwrites all of them.
⚡ One listener on the parent
Write:
list.addEventListener('click', (e) => {
if (e.target.tagName === 'LI') {
e.target.classList.add('done')
}
})
Guess first: does an item added later also get marked when clicked?
Yes. The listener is on the <ul> (that is list), and a click on any <li> travels up to its parent, including a click on a new item.
Meaning: A click on an <li> travels up to its parent, list. So one listener on the parent is enough for many children. This is called event delegation. e.target is the element that was actually clicked. e.target.tagName === 'LI' makes sure the clicked element really is an <li>: tagName is always in capital letters. The listener adds the class done only to the <li> that was clicked.