Check if div exists, if not - check again until it is created

Viewed 1489

I have a div that is created by a plugin and appears after the page is rendered (always at different times).

I need to check if this div exists, then execute a set of functions. However if it does not exist yet, I want to wait(check) until it appears, then execute that set of functions.

Here is what I'm using right now:

var check = setInterval(function(){
  if ($('#target-div').length){
    console.log('execute set of functions')
    clearInterval(check);
  }
}, 100);

However, is there a way to permanently check if the div exits (like running it in the background or something) and as soon as it gets created - stop, but without setInterval?

Because I have multiple similar checks and it gets a total mess having to set a new/different setInterval each time.

Thanks.

1 Answers

Don't use DOM polling to do this as it's an anti-pattern. Use a Mutation Observer instead. This is a listener which can be set to trigger when certain changes are made to the DOM, eg. child node or attribute amendments. Try this:

var $div = $("#container");

new MutationObserver(function(mutations) {
  console.log('.foo was appended');
}).observe($div[0], {
  childList: true
});

setTimeout(function() {
  $div.append('<div class="foo">foo</div>');
}, 2000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  Appending an element in 2 seconds...
</div>

Note that this is a very basic example. You can tune the handler function you provide to MutationObserver() in any way required, as the mutations parameter provides a lot of information about what change just occurred.

See the MDN documentation link above for further information.

Related