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.
array.splice([indexOfElement], [noOfElemToDel], [newElemToAdd])
[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
If you are new to the
To delete an element from an array using the
splice() method, create an
We have a
span element with an ID that will display the number of items in our todo. We also have a
From the code above:
We have the
todosArr which contains our to-dos.
Next, we grab the
document.getELementById() from the DOM.
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
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 takes the index of any element of the to-do and uses the
splice method to remove such element from the array.
When this is done, the
createTodo() function is called again to reload the elements now currently in the
window.addEventListener("load") is called so as to load the elements to the DOM before the page loads completely.
Take a look at the demo below:
View all Courses