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?
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With