Site icon Puneet Sharma – Freelance Web Developer

How to detect if node is added or removed inside a DOM element

document.getElementById("myDiv").addEventListener("DOMNodeInserted DOMNodeRemoved", function(event) {
  console.log("A new node has been inserted or removed.");
});

To use these events, you can bind a function to the DOMNodeInserted or DOMNodeRemoved event of a specific element or the entire document. For example, you can bind a function to the DOMNodeInserted event of a specific div element to trigger an action whenever a new node is added to that div.

It’s important to note that the DOMNodeInserted and DOMNodeRemoved events are deprecated and should not be used in modern web development. Instead, you should use the MutationObserver API, which provides a more flexible and efficient way of detecting changes to the DOM tree. The MutationObserver API allows you to monitor specific elements and their attributes, and provides more fine-grained control over when events are triggered.

Exit mobile version