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:
.onclick
We can then set our onclick to call a function that will remove the item when it is clicked, like this:
<!DOCTYPE html> <html> <head> <title>To-Do List App</title> <script> function addItem() { var newItem = document.createElement("div"); newItem.innerHTML = document.getElementById("box").value; newItem.onclick = removeItem; document.getElementById("list").appendChild(newItem); } function removeItem() { document.getElementById("list").removeChild(this); } </script> </head> <body> <p>Special Exhibition To-Do List</p> <input type="text" id="box" value="Type here to add task"/> <br/> <input type="button" value="Add item" onclick="addItem();"/> <div id="list"></div> </body> </html>
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.