Home >Web Front-end >JS Tutorial >How Can I Detect and Respond to Added Elements in the DOM?

How Can I Detect and Respond to Added Elements in the DOM?

Barbara Streisand
Barbara StreisandOriginal
2024-12-15 19:05:15143browse

How Can I Detect and Respond to Added Elements in the DOM?

Detecting DOM Changes for Added Elements

Introduction

To respond to changes in the Document Object Model (DOM), developers often need to execute functions when elements are added to the HTML. This article provides a solution using MutationObserver, offering both an advanced approach that works on modern browsers and a fallback method for legacy browsers.

The Advanced Approach: MutationObserver

MutationObserver is an API that allows you to observe and respond to specific changes in the DOM. For detecting added elements, observeDOM(obj, callback) is used, where obj is the target element and callback is the function to be executed upon changes. Here's a code snippet:

var observeDOM = (function() {
  var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

  return function(obj, callback) {
    if (MutationObserver) {
      var mutationObserver = new MutationObserver(callback);
      mutationObserver.observe(obj, {childList: true, subtree: true});
      return mutationObserver;
    }
    // Fallback for legacy browsers
    else if (window.addEventListener) {
      obj.addEventListener('DOMNodeInserted', callback, false);
      obj.addEventListener('DOMNodeRemoved', callback, false);
    }
  }
})();

To utilize observeDOM, provide the DOM element to observe and a callback that receives an array of MutationRecord objects. Each MutationRecord represents a change in the DOM, and you can extract added and removed nodes from it.

Example and Demo

Here's a simplified example where a callback is triggered when an item is added or removed from a list element:

observeDOM(listEl, function(m) {
  var addedNodes = [], removedNodes = [];

  m.forEach(record => record.addedNodes.length && addedNodes.push(...record.addedNodes));
  m.forEach(record => record.removedNodes.length && removedNodes.push(...record.removedNodes));

  console.clear();
  console.log('Added:', addedNodes, 'Removed:', removedNodes);
});

Accompanying this article is a live demo that displays console logs as DOM elements are added or removed, showcasing the functionality of observing DOM changes.

The above is the detailed content of How Can I Detect and Respond to Added Elements in the DOM?. 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