How to detect element class name changes with JavaScript?

Sometimes, we want to detect element class name changes with JavaScript.

In this article, we’ll look at how to detect element class name changes with JavaScript.

How to detect element class name changes with JavaScript?

To detect element class name changes with JavaScript, we can use the MutationObserver.

For instance, we write:

<div class='foo'>

</div>

to add a div.

Then we write:

const mut = new MutationObserver((mutations, mut) => {
  console.log(mutations, mut)
});
const div = document.querySelector("div")
mut.observe(div, {
  'attributes': true
});

setTimeout(() => {
  div.className = 'bar'
}, 1000)

We create a mutation observer object with the MutationObserver constructor.

Then we call observer on it with the div that we want to watch for changes for and an object that has attributes set to true to watch for attribute changes on the div.

Next, we set the className of the div to 'bar'.

As a result, the mutations iterable object should have the target.className that has the new class name value.

Conclusion

To detect element class name changes with JavaScript, we can use the MutationObserver.