Using plain JavaScript (not jQuery), is there a way I can test to see if an element contains a class?
Currently, I'm doing this:
HTML:
<div id="test" class="class1"></div>;
JS:
var test = document.getElementById("test");
var testClass = test.className;
switch(testClass){
case "class1": test.innerHTML = "I have class1"; break;
case "class2": test.innerHTML = "I have class2"; break;
case "class3": test.innerHTML = "I have class3"; break;
case "class4": test.innerHTML = "I have class4"; break;
default: test.innerHTML = "";
}
This results in this output, which is correct:
I have class1
The issue is that if I change the HTML to this...
<div id="test" class="class1 class5"></div>
...there's no longer an exact match, so I get the default output of nothing (""
). But I still want the output to be I have class1
because the <div>
still contains the .class1
class.
Since he wants to use switch(), I'm surprised no one has put this forth yet:
Try this one:
Here is a little snippet If you’re trying to check wether element contains a class, without using jQuery.
This accounts for the fact that element might contain multiple class names separated by space.
OR
You can also assign this function to element prototype.
And trigger it like this (very similar to jQuery’s
.hasClass()
function):I know there a lot of answers but most of these are for additional functions and additional classes. This is the one I personally use; much cleaner and much less lines of code!
See this Codepen link for faster and easy way of checking an element if it has a specific class using vanilla JavaScript~!
hasClass (Vanilla JS)
Here's a case-insensitive trivial solution: