Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

removing new buttons

I am having some problems with a side project of mine. I have a button that genertes todo lists on a list which includes a button. /putting in a name for an Todo list item + button that makes an list item

$("#NewTodo" ).on("click", function() {

//graps what is in the input field
var TaskName = $("#Task_name").val()
$("#ListContainer").append("<li class='listItem'>" + checker + TaskName + Sizing + prior + "<button class='del'>x</button> </li>")

this works fine. I then want to be able to remove the list item again by pressing the button that is in the newly formed list item. with the class ".del" I do this by getting the parent of the button, which should be the li element and removing it.

// being able to delete items buttin

$('.del').on("click", function(){ $(this).parent().remove()

}); //end remove button funciton.

however this does nothing, and I get no errors. My though was that like you would do a document ready function to make sure that JS is loaded after the DOM; by inserting a new DOM element, JS wont work for that because JS is already loaded.

1 Answer

Steven Parker
Steven Parker
243,318 Points

You're right that when the button is created, the function that attaches the handler has already happened.

:point_right: But you can attach a delegated handler to the document body (or any ancestor of the element that will be removed) that will work on elements that are created later, like this:

$(body).on("click", ".del", function(){
    $(this).parent().remove()
});