Home >Web Front-end >JS Tutorial >How Can I Detect and Respond to DOM Changes in JavaScript?
Detect DOM Changes
You can detect changes to the Document Object Model (DOM) using various methods.
1. MutationObserver (Modern Browsers)
const observer = new MutationObserver((mutations) => { // Process mutations here... }); observer.observe(targetElement, { childList: true, subtree: true });
2. Mutation Events (Deprecated, but Still Supported)
targetElement.addEventListener('DOMNodeInserted', (event) => { // Node added }); targetElement.addEventListener('DOMNodeRemoved', (event) => { // Node removed });
Example: Detecting Input Addition
If you specifically want to execute a function when a
const targetElement = document.getElementById('element-to-monitor'); const observer = new MutationObserver((mutations) => { mutations.forEach((mutation) => { if (mutation.type === 'childList' && mutation.addedNodes.length > 0) { const addedNodes = mutation.addedNodes; Array.from(addedNodes).forEach((node) => { if (node.nodeName === 'DIV' || node.nodeName === 'INPUT') { // Execute your function here... } }); } }); }); observer.observe(targetElement, { childList: true, subtree: true });
The above is the detailed content of How Can I Detect and Respond to DOM Changes in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!