Skip to content

Instantly share code, notes, and snippets.

@samMeow
Last active March 18, 2019 02:11
Show Gist options
  • Save samMeow/f7d4480904e05d607fa0fd9e96d3c154 to your computer and use it in GitHub Desktop.
Save samMeow/f7d4480904e05d607fa0fd9e96d3c154 to your computer and use it in GitHub Desktop.
const elementExistPromise = (selectorFunc, parent = document.body) => {
const exists = selectorFunc(parent);
if (exists && exists.length !== 0) {
return Promise.resolve(exists);
}
return new Promise(resolve => {
const mu = new MutationObserver((list, me) => {
const record = list.find(({ target }) => {
const x = selectorFunc(target);
return x && x.length !== 0;
});
if (record) {
me.disconnect();
resolve(selectorFunc(record.target));
}
});
mu.observe(parent, {
childList: true,
subTree: true,
attributes: true,
});
});
};
const findNode = (fn, node) => {
if(fn(node)) {
return node;
}
for (let i = 0; i < node.children.length; i ++) {
const child = findNode(fn, node.children.item(i))
if (child) {
return child
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment