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
Linda HamiltonOriginal
2024-12-15 01:54:09685browse

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

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 });

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!

Statement:
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