Nice one, @tim-khorev !
Another approach I’ve used a lot is document.getElementsByClassName(). If you’re dealing with multiple elements that share the same class, this method can be especially handy. It returns a live HTMLCollection, meaning if the DOM changes, the collection is automatically updated.
window.onload = function() {
var elements = document.getElementsByClassName("demo-class");
if (elements.length > 0) {
console.log("Element exists");
} else {
console.log("Element does not exist");
}
};
This approach works well when you’re expecting to find several elements. Just check the length property—if it’s greater than 0, you know the element(s) are there.