Time for action – removing a task from the list
Now that we can add tasks to the list, let's add the ability to remove tasks. To do this we'll need a delete button for each task in the list. We'll add the code to create the button in the addTaskElement()
method. You can find the code for this section in Chapter 1/example1.2
.
function addTaskElement(taskName) { var $task = $("<li></li>"); var $delete = $("<button class='delete'>X</button>"); $task.append($delete) .append("<span class='task-name'>" + taskName + "</span>"); $delete.click(function() { $task.remove(); }); }
The first thing this method does is create a new <button>
element with a class of delete
. Then it creates the list item element as we did before, except that first it appends the delete button and then appends the task name. Note that we are now wrapping the task name in a <span class=
'task-name
'>
element to help us keep track of it. Last we add a click event handler to the delete button. To delete the task from the list element we simply call the remove()
method to remove it from the DOM. Voila, it's gone!