Skip to content

Instantly share code, notes, and snippets.

@mohit-raj-purohit
Created April 18, 2023 17:49
Show Gist options
  • Save mohit-raj-purohit/d8e1841b5064225b354f4aff107b7e7c to your computer and use it in GitHub Desktop.
Save mohit-raj-purohit/d8e1841b5064225b354f4aff107b7e7c to your computer and use it in GitHub Desktop.
MutationObserver: DOM Mutation Events in JavaScript
<!DOCTYPE html>
<html>
<body>
<ul id="item-list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<button id="add-button">Add Item</button>
<script>
// Select the target node
const itemList = document.getElementById('item-list');
// Create a new MutationObserver instance
const observer = new MutationObserver(function(mutationsList) {
// Loop through the list of mutations
for (const mutation of mutationsList) {
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
// Handle the added item
console.log('New item added:', mutation.addedNodes[0].textContent);
}
}
});
// Configure the observer to observe changes to the child nodes of the target node
const config = { childList: true };
// Start observing the target node
observer.observe(itemList, config);
// Add a click event listener to the "Add Item" button
const addButton = document.getElementById('add-button');
addButton.addEventListener('click', function() {
// Add a new item to the list
const newItem = document.createElement('li');
newItem.textContent = 'Item ' + (itemList.children.length + 1);
itemList.appendChild(newItem);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment