-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwaitForElement.js
More file actions
43 lines (38 loc) · 1.02 KB
/
waitForElement.js
File metadata and controls
43 lines (38 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* waitForElement
* @param {string} selector
* @returns a promise with the first matching element
*/
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 });
});
}
/**
* Example Usage:
*/
waitForElement('.hey-brian').then(function(el) {
console.log('hey brian el', el)
});
setTimeout(function() {
let div = document.createElement('div');
div.classList.add('hey-brian');
document.body.appendChild(div);
}, 2500);