1

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.

1
  • You need to delegate the event handler higher up the DOM tree. Read the .on() docs. Commented Jan 14, 2013 at 21:12

1 Answer 1

1

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.
    */
});
Sign up to request clarification or add additional context in comments.

2 Comments

Oh thank's so much!! I still don't get (and did not get when I read the documentation) what the the delegate does. I mean, I thought I had to link the listener to my .remove css class, then set the event (click), and call the function. So since .on() has to be linked to the document, the delegate tells which element of the DOM to look for?
@ghego1 you can delegate from any parent element (doesn't have to be document)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.