Last active
January 20, 2021 10:25
-
-
Save vaaski/57cc3ca7446ddc81ea2bd919473456cf to your computer and use it in GitHub Desktop.
get an element with querySelector or wait for it using MutationObserver
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
| /** | |
| * get an element with querySelector or wait for it using MutationObserver | |
| * @param {string} selector a css selector | |
| * @param {HTMLElement} parent the parent in which to search for | |
| * @returns {Promise<HTMLElement>} | |
| */ | |
| const getElement = (selector, parent = document) => { | |
| return new Promise(res => { | |
| let query = parent.querySelector(selector) | |
| if (query) return res(query) | |
| let timeout = 0 | |
| const observer = new MutationObserver((list, obs) => { | |
| for (const mutation of list) { | |
| if (mutation.type === "childList") { | |
| query = parent.querySelector(selector) | |
| if (query) { | |
| obs.disconnect() | |
| clearTimeout(timeout) | |
| return res(query) | |
| } | |
| } | |
| } | |
| }) | |
| observer.observe(parent, { childList: true, subtree: true }) | |
| timeout = setTimeout(() => { | |
| observer.disconnect() | |
| console.log(`observer for ${selector} timed out`) | |
| return res(document.createElement("div")) | |
| }, 5e3) | |
| }) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment