To add onload event to a div element with JavaScript, we use the MutationObserver
constructor.
For instance, we write
const observer = new MutationObserver((mutationList, obsrvr) => {
const divToCheck = document.querySelector("#foo");
if (divToCheck) {
console.log("div is loaded now");
obsrvr.disconnect();
return;
}
});
const parentElement = document.querySelector("parent-static-div");
observer.observe(parentElement, {
childList: true,
subtree: true,
});
to create the observer
object by calling MutationObserver
with a callback that checks if the element with ID foo with querySelector
.
Then we check if it’s not null
with the if statetment.
If it’s not null, then we call disconnect
to disconnect the observer.
Next, we select its parent element with querySelector
.
And then we call observer.observe
with the parentElement
and an object that has childList
and subtree
set to true
to watch for changes of the elements down the hierarchy.