How can I check in JavaScript if an element has class?

How can I JavaScript check if an element has class?

For example, if I have the following HTML:

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

I want to determine if this

contains the class class1. How can I do this without requiring an exact match?

The simplest and most efficient way to check if an element has a specific class is to use the classList property with the contains() method. This method returns true if the class exists on the element.

var element = document.getElementById("test");
if (element.classList.contains("class1")) {
console.log("The element contains class1.");
}