Detect if a class has been added ( JavaScript )
Detecting if a class has been added to an element. Vanilla JavaScript, using MutationObserver interface.
Example:
A class of "class-name-added" is added to a div in 3 seconds after the page is loaded. Once it is detected, the name of the last class added to the element (that is, "class-name-added") is printed inside the div.
HTML code:
<div class="example">
</div>
JavaScript code:
<script>
// Adding .class-name-added class to an element
window.addEventListener('load', function () {
var exists = setInterval ( function () {
clearInterval ( exists );
document.querySelector('.example').classList.add('class-name-added');
}, 3000);
});
// Detecting if the class has been added and printing its name
var mutationTarget = document.querySelector('.example');
var mutationObserverConfig = { attributes: true };
var callback = function ( mutations ) {
for( var mutation of mutations ) {
if ( mutation.attributeName === 'class' ) {
if ( mutation.target.classList.contains('class-name-added') ) {
document.querySelector('.example').textContent = mutation.target.classList[ mutation.target.classList.length-1 ];
}
}
}
};
var observer = new MutationObserver ( callback );
observer.observe ( mutationTarget, mutationObserverConfig );
</script>
Browser support
- Windows
- Edge 12.0+
- Firefox 14.0+
- Google Chrome 38.0+
- Opera 25.0+
- Safari 7.0+
- Linux
- Firefox 14.0+
- Google Chrome / Chromium
- Opera 25.0+
More
- Adding a class to all sibling elements of a specific type in JavaScript
- Append an element after a specific element in JavaScript
- Array to string in JavaScript
- Calculate sum of HTML table column in JavaScript
- Detecting a newly generated element and adding a class to it in JavaScript
- Generating an HTML list out of page headings in JavaScript
- Getting the last class name in classList collection
- Removing the last character from a string in Javascript
- Transliterating Russian to English in JavaScript
- Wrap each character of a string in <span> tag (JavaScript)
- Wrap each word of text in <span> tag (JavaScript)