KOMPX.COM or COMPMISCELLANEA.COM   

Detecting a newly generated element and adding a class to it in JavaScript

Detecting an element generated some time after the whole page has been fully loaded. Pure JavaScript, employing MutationObserver interface.

Example:

A paragraph with class "generated" is created in 3 seconds after the page is loaded. This element is detected and another class "red-background" is added to it, making its background red.

HTML code:


<div class="example">
</div>

JavaScript code:


<script>
// Creating .generated element and adding it to document
window.addEventListener('load', function() {
	let exists = setInterval(function() {
		clearInterval(exists);
		document.querySelector('.example').insertAdjacentHTML('afterbegin', '<p class="generated"></p>');
	}, 3000);
});
	
// Function to wait for an element and to detect it	
function waitForElement(selector) {
	return new Promise(resolve => {
		if (document.querySelector(selector)) {
			return resolve(document.querySelector(selector));
		}

		const observer1 = new MutationObserver(mutations => {
			if (document.querySelector(selector)) {
				resolve(document.querySelector(selector));
				observer1.disconnect();
			}
		});

		observer1.observe(document.body, {
			childList: true,
			subtree: true
		});
	});
};

// Adding a class to .generated element, when it has been detected
waitForElement('.generated').then((element) => {	
	document.querySelector('.generated').classList.add('red-background');
});
</script>

CSS code:


.generated {height: 20px; width: 100%; background: #999;}
.red-background {background: #f00;}

Browser support
Windows
Edge 12.0+
Firefox 29.0+
Google Chrome 33.0+
Opera 20.0+
Safari 7.1+
Linux
Firefox 29.0+
Google Chrome / Chromium
Opera 20.0+
More