Reputation: 2317
I'm trying to change the class name on divs where a specific class name exists.
The problem I'm finding is that if a class name doesn't exist on a div the browser throws up an error.
function cardUnfocus() {
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++){
if (document.getElementById(divs[i]).className != null) {
if (document.getElementById(divs[i]).className == "container_selected")
document.getElementById(divs[i]).className = "container";
}
}
}
What is an elegant way to check if a class exists? (not using jQuery)
Upvotes: 1
Views: 44
Reputation: 9431
You can use classList:
element.classList.contains('name-of-class');
Upvotes: 1