Home  >  Article  >  Web Front-end  >  How can I detect Attribute Changes in the DOM?

How can I detect Attribute Changes in the DOM?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-26 16:59:03409browse

How can I detect Attribute Changes in the DOM?

Detecting Attribute Changes in the DOM

Question:

Is it possible to initiate an event, such as a custom event, when an attribute of an HTML element changes? More specifically, when the src attribute of an image () element or the innerHTML attribute of a division (

) element is modified?

Answer:

Mutation Events (Deprecated)

Historically, DOM Mutation Events were used to monitor attribute changes. However, they have been deprecated since 2012. Their replacement, MutationObserver, is recommended.

MutationObserver

MutationObserver is an advanced API that enables you to observe changes to the DOM. It provides finer-grained control than Mutation Events and allows you to track specific elements, mutations, and tree structures.

Example withMutationObserver:

<code class="javascript">// Create a new MutationObserver instance
const observer = new MutationObserver((mutationsList) => {
  for (const mutation of mutationsList) {
    // Check if the mutation is an attribute change
    if (mutation.type === "attributes") {
      console.log(`Attribute changed on ${mutation.target.nodeName}`);
    }
  }
});

// Start observing the document body for attribute changes
observer.observe(document.body, { attributes: true });</code>

jQuery Event Plugin

The Mutation Events plugin for jQuery can also be used to detect attribute changes. It provides an easier-to-use API for basic use cases.

Example with jQuery Mutation Events Plugin:

<code class="javascript">$("img").on("attrchange", (e) => {
  console.log(`Image src changed to ${e.target.src}`);
});</code>

Note:

Browser support for DOM Mutation Events varies. It's always recommended to check compatibility before relying on this functionality.

The above is the detailed content of How can I detect Attribute Changes 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