Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (20.3k points)

Using plain JavaScript (no jQuery), Is there any way to check if an element contains a class?

Currently, I'm doing this:

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 = "";

}

<div id="test" class="class1"></div>

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.

1 Answer

0 votes
by (40.7k points)

Try using .contains method like this:

test.classList.contains(testClass);

Related questions

Browse Categories

...