Based on this Q&A, I try to write some native JS code (no use of libraries) that will have elements addition hierarchy/dependency, which means that I'll have to wait for some elements to show up/load before I go on with the function. I have the following function to create and use MutationObservers
in order to track DOM changes:
/**
* Creates an observer that tracks added DOM elements and executes a function when they're added
* @param {HTMLElement} observedObject - the dom element to observe
* @param {Function} elementFunc - the function to execute when elements are added
* @param {Number} timeoutMs - the amount of miliseconds to wait before disconnecting the observer
*/
function observeDOM(observedObject, elementFunc, timeoutMs) {
var connected = false;
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (!mutation.addedNodes) return
for (var i = 0; i < mutation.addedNodes.length; i++) {
if(elementFunc(mutation.addedNodes[i])) {
// disconnect when the function returns true
observer.disconnect();
break;
}
}
})
});
observer.observe(observedObject, {
childList: true
, subtree: true
, attributes: false
, characterData: false
});
connected = true;
// disconnect the observer after N seconds
if(timeoutMs >= 0) {
setTimeout(function() {
if(connected) {
observer.disconnect();
connected = false;
}
}, timeoutMs);
}
}
And I use the function above like that:
// do some staff...
observeDOM(document.body, function(node) {
if(node.className === "class1") {
// do some staff and wait for another element
observeDOM(document.body, function(node) {
if(node.className === "class2") {
// do some staff and wait for another element
observeDOM(document.body, function(node) {
if(node.className === "class2") {
//[...]
return true;
}
return false;
}
return true;
}
return false;
}
return true; // stop the observer
}
return false; // go on listening to elements addition
}
Do you think there is more elegant way to achieve it? What bothers my eyes the most is the tonnes of nested block I'll create when I have a big amount of elements to wait for !