Last active
January 31, 2021 16:41
-
-
Save Dobby89/baa643aa2eff5303d5ba1b1b2718c388 to your computer and use it in GitHub Desktop.
Wait for an element to exist
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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