say I have <ul>
, I need to listen/watch when an <li>
was removed and added.
Asked
Active
Viewed 1,357 times
3

h3n
- 5,142
- 9
- 46
- 76
-
Question already answered here: (https://stackoverflow.com/questions/7782565/jquery-trigger-event-on-children-size-change) – Gicu Aftene Aug 02 '22 at 09:50
-
That question doesn't have an up-to-date answer, a lot has changed in 11, or 7 years – Jack_Hu Aug 02 '22 at 09:52
-
1If you can, you should dispatch a custom event yourself when a ```
- ``` is added or removed.
– Shrimp Aug 02 '22 at 10:02
2 Answers
5
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>

Jack_Hu
- 857
- 6
- 17
-
-
The MDN article, which in turn was take from a blog. It's all in the link. – Jack_Hu Aug 03 '22 at 08:39
0
Actually, i can't understand your question totally but there's an answer in my mind:
let ul = [];
ul[0] = Array.from(document.getElementById("myUl").children);
ul[1] = ul[0].length;
//Make an event to when to listen it e.g. setInterval
if (ul[0] < ul[1].length) { console.log("an li removed"); }
else if (ul[0] > ul[1].length) { console.log("an li added"); }

Mohammad Maaz
- 56
- 8