Source Code:
(back to article)
Submit
Result:
Report an issue
<!DOCTYPE html> <html> <head> <title>Exploring DOM Changes: Live Examples with Mutation Observers</title> </head> <body> <div id="target" style="background-color: lightgray; padding: 10px;"> Watch this space for changes! </div> <button style="margin-top: 10px;" onclick="addNewElement(); changeAttribute();">Add New Element and Change Color</button> <div id="log" style="margin-top: 20px;"></div> <script> // Get the element to observe const targetNode = document.getElementById('target'); // Define configurations for the observer const config = { attributes: true, childList: true, subtree: true, attributeOldValue: true }; // Callback function to execute when mutations are observed const callback = function(mutationsList, observer) { for (const mutation of mutationsList) { const message = document.createElement('p'); if (mutation.type === 'childList') { message.textContent = 'A child node has been added or removed.'; message.style.color = 'green'; } else if (mutation.type === 'attributes') { message.textContent = 'The ' + mutation.attributeName + ' attribute was modified.'; message.style.color = 'blue'; } document.getElementById('log').appendChild(message); } }; // Create an observer instance linked to the callback function const observer = new MutationObserver(callback); // Start observing the target node for configured mutations observer.observe(targetNode, config); // Function to add new elements function addNewElement() { const newElement = document.createElement('div'); newElement.textContent = 'New element added!'; targetNode.appendChild(newElement); } // Function to change attributes function changeAttribute() { const currentColor = targetNode.style.backgroundColor; targetNode.style.backgroundColor = currentColor === 'lightgray' ? 'lightblue' : 'lightgray'; } </script> </body> </html>