<div id='main'></div>
<div id='out' style="color:red"></div>
<button id='add'>add item</button>
<button id='remove'>remove last</button>
<script>
var callback = (mutationsList) => {
for (var mutation of mutationsList) {
// если добавление или удаление Node
if (mutation.type === 'childList') { // если добавление
if (mutation.addedNodes.length > 0) {
let [firstnode] = mutation.addedNodes
firstnode.addEventListener('click', click)
} else if (mutation.removedNodes.length > 0) { // если удаление
let [firstnode] = mutation.removedNodes
firstnode.removeEventListener('click', click)
}
}
}
}
var main = document.getElementById('main')
var observer = new MutationObserver(callback)
var config = { attributes: false, childList: true, subtree: false }
observer.observe(main, config)
var click = (e) => document.getElementById('out').innerHTML = e.target.id
document.getElementById('add').addEventListener('click', (e) => {
var item = document.createElement('div')
item.id = `item ${main.querySelectorAll('*').length}`
item.innerHTML = item.id
main.appendChild(item)
})
document.getElementById('remove').addEventListener('click', (e) => {
var items = main.querySelectorAll('*')
items.length > 0 && main.removeChild(items[items.length - 1])
})
</script>