![]() |
VOOZH | about |
Detecting the nodes when they are added or removed from the DOM (Document Object Model) element is a common requirement in web development. It allows developers to respond dynamically to the changes in the DOM structure enabling features such as live updates, event delegation, and more.
You can utilize the below approaches to detect the changes in the DOM:
Table of Content
The Mutation Observer API provides a way to asynchronously observe changes in the DOM. It allows developers to specify a callback function that gets invoked whenever mutations occur within the target element.
Example: The below code implements the mutation observer API to detect changes in the DOM.
Output:
The Event listeners can be attached to the specific events like DOMNodeInserted and DOMNodeRemoved to detect the node additions and removals within the DOM element. However, these events are deprecated and not recommended for the use in the modern web development.
Example: This example demonstrates how to detect changes to the DOM node using event listeners in JavaScript.
Output: