user623520
user623520

Reputation:

check if element exists after ajax load

It's Friday morning and my brain appears to be malfunctioning.

I would like to execute a load of script, but only when a certain element is present on the page. This may have also been loaded via ajax. Which means when I do something like:

if ($('#foo').length > 0) {
    // Do stuff
});

It will only load on direct page loads, not ajax... obviously. I just can't think of the how to trigger this check after an ajax load.

Thanks

Upvotes: 3

Views: 9322

Answers (1)

lonesomeday
lonesomeday

Reputation: 238115

You can do a check after every AJAX request by using ajaxComplete:

$(document).ajaxComplete(function() {
    if ($('#foo').length) {
        // do stuff
    }
});

Upvotes: 10

Related Questions