JSFiddle - React, Tailwind, and code Playground
by philll_t
HTML
<div id="watchme">
<button id="new_element">
Create a new element
</button>
</div>
JavaScript
const onElementCreated = function (watch_selector, findCallback, callback) {
const changeCallback = function (mutationList) {
let found = false;
mutationList.forEach(mutation => {
if (mutation.type === "childList") {
found = Array.from(mutation.addedNodes).find((n) => findCallback(n));
}
});
// Do something
if(found) {
callback(found);
}
}
const observer = new MutationObserver(changeCallback);
observer.observe(document.querySelector(watch_selector), {childList: true});
return observer;
}
let observer;
observer = onElementCreated("#watchme", (node) => node.name === 'first', function () {
console.log("Created!");
observer.disconnect();
});
const addElementToBody = function () {
// Add new element to body;
const newElement = document.createElement("div");
newElement.append("Hey");
newElement.name = "first"
document.querySelector("#watchme").append(newElement);
}
const button = document.querySelector("#new_element");
button.addEventListener("click", addElementToBody);