Skip to content

Instantly share code, notes, and snippets.

@rajivmehtaflex
Forked from PaulKinlan/waitForElement.js
Created October 16, 2016 04:50
Show Gist options
  • Save rajivmehtaflex/3d1d96f27df600bfeab05c6a4406b84e to your computer and use it in GitHub Desktop.
Save rajivmehtaflex/3d1d96f27df600bfeab05c6a4406b84e to your computer and use it in GitHub Desktop.
waitForElement.js
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 });
});
}
@rajivmehtaflex
Copy link
Author

It is pretty simple to use this simple API.

waitForElement("#test").then(function(element) {
console.log("Element Added", element);
});
Now combining in the monitorEvents function from my previous post, I can now set a breakpoint early in the lifecycle of a page (because scripts in the head block) and set up a waitForElement call that can now start logging all the events that are firing on that element.

waitForElement("#test").then(function(element) {
monitorEvents(element);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment