Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait until an element exists?

I'm working on an Extension in Chrome, and I'm wondering: what's the best way to find out when an element comes into existence? Using plain javascript, with an interval that checks until an element exists, or does jQuery have some easy way to do this?

like image 279
mattsven Avatar asked Apr 02 '11 18:04

mattsven


People also ask

How to wait until an element exists JavaScript?

To wait to do something until an element exists in the DOM, you can use JavaScript MutatationObserver API. As the name suggests, it can be used to listen out for changes in the DOM. You can then fire a (callback) function in response to this.


1 Answers

DOMNodeInserted is being deprecated, along with the other DOM mutation events, because of performance issues - the recommended approach is to use a MutationObserver to watch the DOM. It's only supported in newer browsers though, so you should fall back onto DOMNodeInserted when MutationObserver isn't available.

let observer = new MutationObserver((mutations) => {   mutations.forEach((mutation) => {     if (!mutation.addedNodes) return      for (let i = 0; i < mutation.addedNodes.length; i++) {       // do things to your newly added nodes here       let node = mutation.addedNodes[i]     }   }) })  observer.observe(document.body, {     childList: true   , subtree: true   , attributes: false   , characterData: false })  // stop watching using: observer.disconnect() 
like image 97
hughsk Avatar answered Sep 23 '22 08:09

hughsk