appendChild and removeChild
Learn to append and remove an element from another.
Adding with appendChild
To place an element on the page, you use the appendChild method. You call it on a parent element and pass the child to add as a parameter.
const list = document.querySelector('ul');
const item = document.createElement('li');
list.appendChild(item);The element becomes the last child of the parent. If you add the same element again, it is removed from its old spot and moved to the new one; it is not duplicated.
Removing with removeChild
To remove an element from the page, you use the removeChild method. It is also called on the parent and takes the child to remove as a parameter.
const list = document.querySelector('ul');
const item = list.querySelector('li');
list.removeChild(item);You must know the parent of the child. So you often reach the parent with child.parentElement and then call removeChild.
Exercise Append an item to the list
The list variable points to a <ul> element. Create a new <li> element named item, assign a short text to its textContent, and append it to list.
Show example solution
const item = document.createElement('li');
item.textContent = 'Milk';
list.appendChild(item);
Test yourself
-
Which adds item to list?
const list = document.querySelector('ul'); const item = document.createElement('li'); // A item.appendChild(list); // B list.appendChild(); // C item.appendChild('list'); // D list.appendChild(item);- A
- B
- C
- D
Show answer
D — Correct! It is parent.appendChild(child) in that order.
-
Append the element to the list
const list = document.querySelector('ul'); const item = document.createElement('li'); list.____(item);Show answer
const list = document.querySelector('ul'); const item = document.createElement('li'); list.appendChild(item); -
Match methods to their effects
- appendChild(child)
- Adds child at the end
- removeChild(child)
- Removes the child
- querySelector(sel)
- Selects the first match