Q:

How to Check If an Element Contains a Class in JavaScript

0

How to Check If an Element Contains a Class in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the contains() Method

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>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Create a Two Dimensional Array in JavaScrip... >>
<< How to Get the Length of a JavaScript Object...