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
- Accessing the first element in forEach loop (JavaScript)
- 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
- Detect if a class has been added (JavaScript)
- Generating an HTML list out of page headings in JavaScript
- Get the current URL in JavaScript
- Getting the last class name in classList collection
- Remove all attributes of an element
- 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)