Deleting Todo Items
Topic Overview and Actualization
Hi, and welcome to our new lesson on Deleting todo items in JavaScript. This is an important capability to understand as it's a common functionality in many applications. By the end of this lesson, you will learn how to remove an item from the HTML page.
Picture this: you've finished your math homework and want to remove it from your todo list. Or perhaps you've just finished washing your car and want to mark it off your list. This is what we aim to achieve in this lesson — providing users the ability to delete completed tasks from their todo list.
Understanding Deletion of an HTML Element
Before we start, let's look at a basic example of how to remove an HTML element. Imagine a user clicks on a task, and we need to remove that task's HTML representation from the webpage. To achieve this, we will use JavaScript!
In JavaScript, there are two primary methods for deleting an HTML element: removeChild() and remove(). Keep in mind that we call these methods because they perform specific tasks or operations. It's a little bit like a machine in a factory — we provide the machine with resources, it does its job, and produces an output.
Here's our HTML structure:
Suppose we want to remove the li element with id item1. First, we need to get a reference to the parent node (the ul element with id todoList). Then, we'll obtain a reference to the child node (the li element with id item1). Finally, we can use the removeChild() method to remove the child node from the parent node:
Alternatively, you can directly call the remove() method on the element you wish to delete:
Both methods will modify the HTML structure to:
It is is important to note that when a parent node is deleted from the DOM, all of its child nodes are also automatically removed along with it. No matter the approach, the li element with id item1 is successfully removed!
Coding the Delete Function in the Todo List Application
