Categories
JavaScript Answers

How to add onload event to a div element with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *