Wait for an element to exist (via Mutation Observer)

function waitForElement(selector) { return new Promise(function(resolve, reject) { var element = document.querySelector(selector); if(element) { resolve(element); return; } var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { var nodes = Array.from(mutation.addedNodes); for(var node of nodes) { if(node.matches && node.matches(selector)) { observer.disconnect(); resolve(node); return; } }; }); }); observer.observe(document.documentElement, { childList: true, subtree: true }); }); } waitForElement("#element").then(function(element) { console.log("The element " + selector + " arrived!") });

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.