KOMPX.COM or COMPMISCELLANEA.COM   

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