Why is not working .click()?

Hello! There was such problem:

Use this code:
$(".answer-item").click(function() {
$(this).toggleClass("active");
});

And everything works perfectly with elements that were originally written in the html file.

If you create a list of elements thus:
answers.forEach(function(item) {
 $('#answers').append('<p class="answer-item">'+item+'</p>');
});


The code stops working. Any idea why this might happen? (Before creating items is an ajax request, whether it be for him? Console, any errors does not produce, just 0 reaction on clicks).
April 3rd 20 at 18:45
2 answers
April 3rd 20 at 18:47
Solution
And then you think, why? You put a handler on the items, then add new elements, and the processor on them no, it was not intended, right? You need to use delegation:

$(document).on('click', '.answer-item', function() {
$(this).toggleClass("active");
});
April 3rd 20 at 18:49
Solution
$('body').on('click', '.answer-item', function() {
$(this).toggleClass("active");
});

Find more questions by tags JavaScriptjQuery