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.
A simplified oneliner:1
1
indexOf
for arrays is not supported by IE (ofcourse). There are plenty of monkey patches to be found on the net for that.The easy and effective solution is trying .contains method.
This is supported on IE8+.
First we check if
classList
exists if it does we can use thecontains
method which is supported by IE10+. If we are on IE9 or 8 it falls back to using a regex, which is not as efficient but is a concise polyfill.Element.matches()
element.matches(selectorString)
According to MDN Web Docs:
Therefore, you can use
Element.matches()
to determine if an element contains a class.View Browser Compatibility
Just to add to the answer for people trying to find class names within inline SVG elements.
Change the
hasCLass()
function to:Instead of using the
className
property you'll need to use thegetAttribute()
method to grab the class name.This is a little old, but maybe someone will find my solution helpfull: