JavaScript: Listening to a class getting added

Reacting on a class getting added can be done with a mutation observer. Example:

const items = document.querySelectorAll('.item')
const expectedClass = 'active'
const activeObserver = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    if (mutation.target.classList.contains(expectedClass) {
      // Do something
    }
  })
})
items.forEach(item => activeObserver.observe(item, { attributes: true, attributeFilter: ['class'] }))

Note that this is not a generic solution – it makes a few assumptions to simplify things. For other situations, this example will need adjustments.

Dominik Schöler