0

What is the correct way to bind an event to an appended element?

I'm doing it like this (and it is working):

$('#element').on('click', function( event ) {
    $('#anything').append('<div class="delete"></div>');

    $('.delete').on('click', function( event ) {
        $(this).remove();
    });
});

Or should I use a delegated on() for the click on delete event outside of the first on()?

1 Answer 1

1

Try to do like this with event delegation and i believe that you are gonna add the .delete element inside of #element,

$('#element').on('click', function( event ) {
    $('#anything').append('<div class="delete"></div>');
});

$('#anything').on('click', '.deleted' , function( event ) {
    $(this).closest("#element").remove();
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.