MutationObserver class changes

@sliptype – You could do it in the below manner:

const element = document.querySelector('div');
let prevState = element.classList.contains('is-busy');
const observer = new MutationObserver((mutations) => { 
    mutations.forEach((mutation) => {
        const { target } = mutation;

        if (mutation.attributeName === 'class') {
            const currentState = mutation.target.classList.contains('is-busy');
            if (prevState !== currentState) {
                prevState = currentState;
                console.log(`'is-busy' class ${currentState ? 'added' : 'removed'}`);
            }
        }
    });
});

Leave a Comment

tech