WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

How to Check If an Element Contains a Class in JavaScript

Topic: JavaScript / jQueryPrev|Next

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>

Related FAQ

Here are some more FAQ related to this topic:

Advertisements
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties