简体   繁体   中英

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM