John T
John T

Reputation: 1078

jQuery access to appended HTML

I'm appending a section of HTML that is returned from an ajax call to a div element in my code when a button is clicked.

I would like to then have access to those id/class selectors through jQuery.

For instance....

Basic HTML

<div id="codeToGoHere"></div>

First Button OnClick event calls ajax event:

ajaxReturns - "<div id='thisDiv'>blah blah</div><div id='thatDiv'>blah blah</div>"
$("#codeToGoHere").append(ajaxReturns);

Second Button OnClick Event:

$("#thisDiv").css("border", "1px solid red");

This isn't working and I'm presuming because the appended code isn't available when the DOM loads. Is there a way of getting the DOM re-evaluated after it has changed to ensure that I can bind to the new elements that have appeared?

Or... probably a better question, is "how do I make this work?"!

Thanks :-)

Upvotes: 0

Views: 69

Answers (2)

Arindam Nayak
Arindam Nayak

Reputation: 7462

After appending html, you need to bind the event to newly added html. Then it will work. TO bind, you can use this.

$("#thisDiv").click(function() { css("border", "1px solid red"); });

You need to put this function just after the following line.

$("#codeToGoHere").append(ajaxReturns);

Upvotes: 2

matthias_h
matthias_h

Reputation: 11416

As you already suscpected, the div is added later and not in the DOM when the page is loaded, therefore you have to attach the click-event using event-delegation:

$(document).on("click", "#thisDiv", function(){
    $(this).css("border", "1px solid red");
});

As there's no button in your question, I've just set the click-event on the appended div as example, assuming you also append a button.
Instead of $(document) any static parent element can work as container element to delegate the event.

Because it should be avoided to copy/paste on Stackoverflow (even from one's own answers) - I've already answered a similar question here with some further information and jquery reference for event delegation.

Upvotes: 2

Related Questions