don
don

Reputation: 4532

jQuery .on() and ajax

I'm adding elements to a page using the jQuery ajax function, on success I get the response from the server and assign it to an element, like so:

$('#element').html(response);

Then I need jQuery to consider the newly added element. My problem is that it is not in the DOM, so I thought of using .on():

$(".remove").on("click", function(){
  alert($(this).text());
});

But this does not work. Well, it does work, but only on elements that were loaded in the first place with the page, not with the new ones. Shouldn't .on() consider also the "new elements"?

PS actually the "click" event is just for testing, I would need the function to run on mouseover, but as of now I'm trying to understand how to work with new DOM elements added through AJAX.

Upvotes: 1

Views: 46

Answers (1)

Naftali
Naftali

Reputation: 146310

Delegate it. Delegate it. Delegate it.

$(document).on('click', '.remove', function(e){
    /*
       do something when *any* `.remove` element is clicked
       in the document, now and in the future.
    */
});

Upvotes: 1

Related Questions