Operter
Operter

Reputation: 95

A better method to check if an element exists than a `setTimeout` and `.length`

Currently I have a function that clicks an element once it's dynamically generated, the problem is that I'm using something like this:

if($('#element').length){
  $('#element').click();
} else {
  setTimeout(function(){
  $('#element').click();
  }, 500);
}

I keep calling this function until the element appears. Is there a better way to keep checking if an element appeared ? I tried using a loop, but I only ended up crashing the browser with an infinite loop

Upvotes: 3

Views: 941

Answers (2)

aghashamim
aghashamim

Reputation: 561

You can make use of Mutation Observer API to check when an element has been added.

var callback = function(mutations) {
// check the mutations and perform whatever you wish to do
}
var observer = new MutationObserver(callback);
// provide the node that you wish to observe for mutations and the configuration to use
observer.observe(<targetNode>, <config>);
...
...
observer.disconnect();

Edit: Added fiddle as an example where each dynamically added paragraph is echoed as an alert when it's added to the DOM.

jsFiddle - echo dynamically added paragraphs with Mutation Observer API

Upvotes: 2

V. Sambor
V. Sambor

Reputation: 13409

jQuery has a .load() event which is called when the element and all sub-elements have been completely loaded.

$( "#element" ).load(function() {
  // is completely loaded
});

Check here more.

Note: This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.

If the element is not associated with any above, then it should be loaded on dom .ready() event.

Upvotes: 0

Related Questions