Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an event that triggers when a child element was removed and added? [duplicate]

say I have <ul>, I need to listen/watch when an <li> was removed and added.

like image 384
h3n Avatar asked Sep 08 '25 00:09

h3n


1 Answers

Sure, you can use a MutationObserver to watch for changes in a DOM element.

The implementation of it is a little complex to describe in this answer, but the MDN article should provide you with all info you need.

Here's a contrived, and partially stolen example, to give you an idea:

const btnAdd = document.getElementById('btn-add');
const btnRemove = document.getElementById('btn-remove');

// Select the node that will be observed for mutations
const targetNode = document.getElementById('some-id');

btnAdd.addEventListener('click', () => {
  const li = document.createElement('li');
  targetNode.appendChild(li);
});

btnRemove.addEventListener('click', () => {
  targetNode.removeChild(targetNode.children[0]);
});


// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
const callback = function(mutationList, observer) {
    // Use traditional 'for loops' for IE 11
    for (const mutation of mutationList) {
        if (mutation.type === 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type === 'attributes') {
            console.log(`The ${mutation.attributeName} attribute was modified.`);
        }
    }
};

// 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);
<button id="btn-add">Add Item</button>
<button id="btn-remove">Remove Item</button>
<ul id="some-id"></ul>
like image 178
Jack_Hu Avatar answered Sep 09 '25 13:09

Jack_Hu