Removing more than one HTML element

Removing more than one HTML element: Now you can remove a HTML element using the removeChild method.

But what happens if user wants to remove more than one item from his list?

We need to use the DOM and JavaScript so that all the items can be removed from the list when they’re clicked.

To do this we need to add an onclick attribute every time we use the createElement method. You can use a DOM method to set the onclick by using the onclick keyword:


We can then set our onclick to call a function that will remove the item when it is clicked, like this:

<!DOCTYPE html>
 <title>To-Do List App</title>
 function addItem() {
 var newItem = document.createElement("div");
 newItem.innerHTML = document.getElementById("box").value;
 newItem.onclick = removeItem;
 function removeItem() {
 <p>Special Exhibition To-Do List</p>
 <input type="text" id="box" value="Type here to add task"/>
 <input type="button" value="Add item" onclick="addItem();"/>
 <div id="list"></div>

In this example, we’ve created a new < div > using createElement. We’ve stored the < div > in a variable so we can set its innerHTML to whatever item has been typed into the text box.

We then use the DOM to set the onclick attribute of the new item. When this item is clicked, it will call the removeItem function and the item will be removed from the list.

Use your new knowledge to make an app where more than one HTML element can be removed when it’s clicked.

Connected through code, Choose Your Platform!

About the Author: Bernard Aybout

In the land of bytes and bits, a father of three sits, With a heart for tech and coding kits, in IT he never quits. At Magna's door, he took his stance, in Canada's wide expanse, At Karmax Heavy Stamping - Cosma's dance, he gave his career a chance. With a passion deep for teaching code, to the young minds he showed, The path where digital seeds are sowed, in critical thinking mode. But alas, not all was bright and fair, at Magna's lair, oh despair, Harassment, intimidation, a chilling air, made the workplace hard to bear. Management's maze and morale's dip, made our hero's spirit flip, In a demoralizing grip, his well-being began to slip. So he bid adieu to Magna's scene, from the division not so serene, Yet in tech, his interest keen, continues to inspire and convene.