I have set up a mutation observer to monitor changes in the page load. Specifically, I am interested in detecting the moment when a particular element is loaded or exists. This element can be identified by its classname, let's say it's called foo
.
When the element with the classname foo
is detected among the mutated objects, I want to trigger a function.
Here is my current implementation:
mutations.forEach(mutation => {
if (!mutation.addedNodes || mutation.addedNodes[0].className === undefined || mutation.addedNodes[0].className !== 'foo') {
return;
} else {
console.log(mutation.addedNodes[0].className + ' has been loaded!');
}
});
This method technically works: the console log is displayed when all three conditions are met.
However, there are situations where mutation.addedNodes[0]
does not contain any className
data, resulting in the error message:
Cannot read property 'className' of undefined
I understand why this error occurs; sometimes mutations
does not have an addedNodes[0]
or it is indeed undefined. But I'm unsure about the best approach to only trigger the console log (eventually, my function) when all the above conditions are satisfied.
As I continue to learn ES6, I believe there might be a solution that could assist me here, but I'm having trouble finding the most effective way forward.