The checkElementExists()
is an asynchronous function that is used to determine if a specified element exists in the DOM after a given timeout. It takes in two parameters: the element to be checked, specified as a CSS selector, and an optional timeout in seconds. The default value for the timeout is Infinity, which means the function will keep checking until the element exists or the page is closed.
A Promise that resolves to `true` if the element exists, or rejects with `false` if it doesn't exist.
async function checkElementExists(element, timeout = Infinity) {
let startTime = Date.now();
return new Promise((resolve) => {
const intervalId = setInterval(() => {
if (document.querySelector(element)) {
clearInterval(intervalId);
resolve(true);
} else if (Date.now() - startTime >= timeout * 1000) {
clearInterval(intervalId);
resolve(false);
}
}, 100);
});
}
checkElementExists("#newElement", 5)
.then((result) => {
if (result) {
console.log("The element exists!");
} else {
console.log("The element does not exist after 5 seconds");
}
});
The function observeNewElement
uses a MutationObserver to detect when a new element that matches a specified selector has been added to the document, and calls a specified callback function with that element as a parameter.
The function takes two parameters: selector
, which is a string representing the CSS selector for the element to be detected, and callback
, which is the function to be called when the new element is detected.
The function starts by setting the targetNode
to the documentElement
, which is the top-level element of the document. The config
object specifies that the observer should watch for changes to the child nodes of the targetNode
and all of its descendants.
The MutationObserver
is then created with a callback function that will be executed each time a mutation occurs. The callback function loops through each mutation that occurred and checks if there are any added nodes. If there are added nodes, the function retrieves the first added node (assuming that only one node was added at a time). If the added node matches the specified selector, the callback function is called with that node as its parameter.
Finally, the observer is started with the observe
method, which takes the targetNode
and config
as its arguments. This starts the observer, which will continuously check for new elements that match the specified selector.
function observeNewElement(selector, callback) {
const targetNode = document.documentElement;
const config = { childList: true, subtree: true };
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.addedNodes.length > 0) {
const newElement = mutation.addedNodes[0];
if (newElement.matches(selector)) {
callback(newElement);
}
}
});
});
observer.observe(targetNode, config);
}
observeNewElement('div.example', (newElement) => {
console.log('New element added:', newElement);
});