<div id="observed-element">
<p>Elemento Hijo 1</p>
<p>Elemento Hijo 2</p>
</div>
<button id="addNodeBtn">Agregar Nodo</button>
document.addEventListener('DOMContentLoaded', () => {
const targetNode = document.getElementById('observed-element');
const addNodeBtn = document.getElementById('addNodeBtn');
const config = { attributes: true, childList: true, subtree: true };
const callback = function(mutationsList, observer) {
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
console.log('Un nodo hijo ha sido añadido o eliminado.');
} else if (mutation.type === 'attributes') {
console.log(`El atributo ${mutation.attributeName} ha sido modificado.`);
}
}
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
addNodeBtn.addEventListener('click', () => {
const newNode = document.createElement('p');
newNode.textContent = 'Nuevo Elemento Hijo';
targetNode.appendChild(newNode);
});
});
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.