Sometimes, we want to check if an element has been loaded on a page before running a script with JavaScript.
In this article, we’ll look at how to check if an element has been loaded on a page before running a script with JavaScript.
How to check if an element has been loaded on a page before running a script with JavaScript?
To check if an element has been loaded on a page before running a script with JavaScript, we can use the mutation observer.
For instance, we write:
const observer = new MutationObserver((mutationRecords) => {
console.log("change detected");
});
observer.observe(document.body, {
childList: true
})
setTimeout(() => {
const div = document.createElement('div')
document.body.appendChild(div)
}, 100)
to create a MutationObserver
instance.
Then we call observer.observer
with the element we want to observe and an object that sets the items we want to observe,.
We set childList
to true
to watch for DOM item changes.
Next, we create a div and call document.body.appendChild
with div
to append a div to the body element.
And when we did that, we should see 'change detected'
logged.
Conclusion
To check if an element has been loaded on a page before running a script with JavaScript, we can use the mutation observer.