js event element update code example

Example 1: javascript detect when number of elements change

const targetNode = document.body;
const config = { childList: true, subtree: true };

const callback = function(mutationsList, observer) {
    for(let mutation of mutationsList) {
        if (mutation.type === 'childList') {
            // Elements have changed
        }
    }
};

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

Example 2: handling event changes

<button>Act-once button</button>
<script>
  let button = document.querySelector("button");
  function once() {
    console.log("Done.");
    button.removeEventListener("click", once);
  }
  button.addEventListener("click", once);
</script>