Home > Web Front-end > JS Tutorial > How Can I Detect and Respond to DOM Changes in JavaScript?

How Can I Detect and Respond to DOM Changes in JavaScript?

Linda Hamilton
Release: 2024-12-15 01:54:09
Original
683 people have browsed it

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 });
Copy after login

2. Mutation Events (Deprecated, but Still Supported)

targetElement.addEventListener('DOMNodeInserted', (event) => {
  // Node added
});

targetElement.addEventListener('DOMNodeRemoved', (event) => {
  // Node removed
});
Copy after login

Example: Detecting Input Addition

If you specifically want to execute a function when a

or is added to the HTML, here's a practical example:

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 });
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template