Show Output
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Check If Element Has a Specific Class in JavaScript</title> <script> document.addEventListener("DOMContentLoaded", function(){ // Selecting target element var div = document.getElementById("myDiv"); // Performing tests document.write(div.classList.contains("alert") + "<br>"); // Prints: true document.write(div.classList.contains("success") + "<br>"); // Prints: true document.write(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>