You can simply use the contains() method of the Element.classList property to determine or check whether an element contains a class or not in JavaScript.
Let's take a look at an example to understand how it basically works:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test If Element Has a Class Using JavaScript</title>
<script>
document.addEventListener("DOMContentLoaded", function(){
// Selecting target element
var div = document.getElementById("myDiv");
// Performing tests
console.log(div.classList.contains("alert")); // Prints: true
console.log(div.classList.contains("success")); // Prints: true
console.log(div.classList.contains("error")); // Prints: false
});
</script>
</head>
<body>
<!--Sample Element-->
<div class="alert success" id="myDiv">This is a piece of text.</div>
</body>
</html>
Use the
contains()MethodYou can simply use the
contains()method of theElement.classListproperty to determine or check whether an element contains a class or not in JavaScript.Let's take a look at an example to understand how it basically works:
need an explanation for this answer? contact us directly to get an explanation for this answer