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 allowsJavaScriptto 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
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
todosArrwhich contains our to-dos. -
Next, we grab the
spanandulusingdocument.getELementById()from the DOM. -
The
createTodo()function will take anyarrayas a parameter whenever it is called. -
When it is called, it creates a
lielement which will be parent of aspanand abutton. -
The
spanholds the value of the to-do item, and thebuttonis 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 thesplicemethod 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 thetodosArr. -
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: