-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
observe element
32 lines (26 loc) · 919 Bytes
/
observe element
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
function observeElement(element, callback) {
const config = {
attributes: true,
childList: true,
subtree: true,
attributeOldValue: true,
};
const listener = function (mutationsList, observer) {
for (const mutation of mutationsList) {
let type = mutation.type === 'childList' ? 'content' : mutation.type;
let oldValue = mutation.oldValue;
let newValue = null;
if (mutation.type === 'childList') {
newValue = [...mutation.target.childNodes].map((node) => {
return node.nodeName === '#text' ? node.nodeValue : node;
});
} else if (mutation.type === 'attributes') {
newValue = mutation.target.getAttribute(mutation.attributeName)
}
callback({type, oldValue, newValue});
}
};
const observer = new MutationObserver(listener);
observer.observe(element, config);
return () => observer.disconnect();
}