How to delete to-do elements in JavaScript

Why use splice() in JavaScript?

Arrays in Javascript have unconventional methods to delete their elements. For instance, we can use pop(), shift(), or filter(). In this shot, we will use the splice() method because it is easier to use and a good alternative to delete a single element from a to-do list.

Syntax


array.splice([indexOfElement], [noOfElemToDel], [newElemToAdd])

Parameters

  • [indexOfElement]: This is the index position of the element from which you want to start deleting the elements.

  • [noOfElemToDel]: This represents the number of elements you want to delete from the array. This is optional, but we need this in our example.

  • [newElemToAdd]: This is also optional and allows JavaScript to add a new element to the array. We can add more than one new element.


If you are new to the splice() method, take a look at this article on how to use the splice() method in JavaScript.


Code

How to delete a ‘to-do’ from our to-do list

To delete an element from an array using the splice() method, create an HTMLHyperText Markup Language document. Follow the HTML code structure shown below.

Explanation

We have a span element with an ID that will display the number of items in our todo. We also have a ul element with an ID that will contain all our to-dos when we use JavaScript to dynamically display our to-dos.

JavaScript code

Explanation

From the code above:

  • We have the todosArr which contains our to-dos.

  • Next, we grab the span and ul using document.getELementById() from the DOM.

  • The createTodo() function will take any array as a parameter whenever it is called.

  • When it is called, it creates a li element which will be parent of a span and a button.

  • The span holds the value of the to-do item, and the button is given an event listener which fires when it is clicked.

  • Then, this event firing triggers the deleteTodo() function.

  • The deleteTodo() function takes the index of any element of the to-do and uses the splice method to remove such element from the array.


todosArr.splice(index, 1);

  • When this is done, the createTodo() function is called again to reload the elements now currently in the todosArr.

  • window.addEventListener("load") is called so as to load the elements to the DOM before the page loads completely.

Complete code

Take a look at the demo below: