Reputation: 19
I'm trying to select a table element from a website, and I am using document.querySelectorAll() to do so. However, the website, I believe, is retrieving that data from another sever and taking time to do so. Therefore, when I try using querySelectorAll() it comes out as undefined.
I've tried adding some event listeners like window.addEventListener("load"), document.addEventListener("DOMContentLoaded), and window.onload() = funciton().
I think those event listeners don't work because technically the window/DOM content is all officially loaded, but the table I needed is just being inserted later. Is there any way to wait for the table to be loaded so I can access it?
Upvotes: 0
Views: 35
Reputation: 1074266
You can use a mutation observer
to listen for changes to the childList (and possibly subtree) of a parent (or ancestor) of the element that's there when your code runs (in the worst case, body
), then when the observer gets called, check for element X.
Live Example:
// Example if you need to use an ancestor
const ob = new MutationObserver(records => {
const div = document.querySelector(".the-element");
if (div) {
ob.disconnect();
console.log("Got it");
}
});
ob.observe(
document.getElementById("ancestor"),
{
childList: true,
subtree: true // Only need this if it's an ancestor
}
);
// Simulates loading the element later
setTimeout(() => {
const div = document.createElement("div");
div.className = "the-element";
div.textContent = "I'm the element";
document.getElementById("parent").appendChild(div);
}, 800);
<div id="ancestor">
<div id="parent">
Parent
</div>
</div>
Upvotes: 2