<button id="first">Click me first</button>
$('#first').click(function(){
$('body').append('<button id="second">Now click me</button>');
});
$('#second').click(function(){
$(this).hide();
});
When #first is clicked, #second gets appended. When #second gets clicked, I want it to
hide itself.
Why isn’t this working?
It’s not working because
$('#second')does not match anything when it gets executed.Try assigning the click handler to the element before adding to the DOM:
You can also use
onto delegate the event if you need to ‘attach’ the event handler before the element exists.