JavaScript: Listening to a class getting added

Posted . Visible to the public.

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
Last edit
Dominik Schöler
Keywords
observing, notify
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2024-09-16 14:04)