/
/
Listen Added and Deleted Node in HTML DOM
Posted 7 years ago • 373 Dibaca

Listen Added and Deleted Node in HTML DOM

Actually it's not the case that I experienced, but there is a friend of mine from the web designer and who made the static version, let's call it Aab. He has a grid design containing 6 cards, and the number of cards can change from 0 - 6, he wants if the card amounts to 4 and above it will execute certain functions. From there I decided to make a listener in the dom, to detect whether there were cards that were added or removed based on the amount of data available.

The Case

It would be easier if I explain with pictures. Few more here is the shape of the grid I mean above.

The above view is formed from the following elements.

Here you have expectations, when elements with className "col" in the "the-content" id are added or deleted, it will trigger a function.

Problem Solving

Javascript has an interesting API named "MutationObserver" https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver, which allows developers to create listener that will run when there is a DOM change or certain conditions.

const els = document.getElementById("the-content")

// callback on change
const callback = function(mutationsList, observer) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            console.log('A child node has been added or removed.');
        }
    }
}

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

const observer = new MutationObserver(callback);
observer.observe(els, config);

That the code what we need, first make sure target elements is wrapped with div with unique id. And then create some config and callback for MutationObserver. If we have changes on childList should appear in log "A child node has been added or removed.". And

Testing

Note : we are test to delete and added element here via Google Chrome inspect element.

First let's delete one element of it, making sure the logs are out.

And then next test with add, with some elements.

2 actions above is done, and it looks like the listener works well. Now you can use this method if needed.

Note :

Make sure to disconnect observer if you doesn't need that anymore or if leaving to other pages, with this code.

observer.disconnect();

References :


  • https://codepen.io/yussan/pen/xQGzKG?editors=1111
  • https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
MauCoding © 2025 powered by YMG Team