Skip to content

Instantly share code, notes, and snippets.

@Dobby89
Last active January 31, 2021 16:41
Show Gist options
  • Select an option

  • Save Dobby89/baa643aa2eff5303d5ba1b1b2718c388 to your computer and use it in GitHub Desktop.

Select an option

Save Dobby89/baa643aa2eff5303d5ba1b1b2718c388 to your computer and use it in GitHub Desktop.
Wait for an element to exist
function waitForAddedNode(params: {
query: string;
parent: HTMLElement;
recursive: boolean;
done: (el: HTMLElement) => void;
}): void {
if (!window.MutationObserver) {
return;
}
const docMutationObserver = new MutationObserver(() => {
const el = params.parent.querySelector(params.query);
if (el) {
params.done(el);
if (docMutationObserver && docMutationObserver.disconnect) {
// tidy up the mutation observer
docMutationObserver.disconnect();
}
}
});
docMutationObserver.observe(params.parent || document, {
subtree: !!params.recursive,
childList: true,
});
}
waitForAddedNode({
query: '#myDynamicElement',
parent: document.body,
recursive: false,
done: function (el) {
console.log('element is now in the DOM', {el})
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment