Добавление нового элемента не имеет ничего общего с атрибутами, и вы не можете наблюдать мутации в элементе, которого еще нет в DOM.
Вместо этого вы ищите childList
модификациина родительском элементе div
будет добавлено внутри (или childList
+ subtree
на предке, если вы не можете непосредственно наблюдать за родителем - если необходимо, предком может быть даже document.body
).
Вот пример непосредственного наблюдения за родителем:
// Set up the observer on the container
let observer = new MutationObserver(function() {
// Does the div exist now?
const div = document.querySelector(".show-pl");
if (div) {
// Yes, "remove" it (you're really just hiding it) and release this observer
console.log("The div has appeared, hiding and releasing observer");
div.style.display = "none";
observer.disconnect();
observer = null;
}
});
observer.observe(document.getElementById("the-parent"), {
childList: true
});
console.log("Watching for the element");
// On a delay, create the div
setTimeout(() => {
console.log("Creating the div");
const div = document.createElement("div");
div.textContent = "Hi there!";
div.className = "show-pl";
document.getElementById("the-parent").appendChild(div);
}, 800);
<div id="the-parent"></div>
Для просмотра предка вместо этого вы должны использовать предка в вызове observe
и добавить subtree: true
к параметрам инициализации.