Check if event.target has specific Class using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Check if event.target has specific Class using JavaScript #

To check if event.target has specific class, call the classList.contains() method on the target object, e.g. event.target.classList.contains('box1'). The method returns a boolean result - true if the class is contained in the element's class list and false otherwise.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> .box { background-color: salmon; height: 100px; width: 100px; margin: 10px; } </style> </head> <body> <div class="box box1">Box 1</div> <div class="box box2">Box 2</div> <div class="box box3">Box 3</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
document.addEventListener('click', function handleClick(event) { const hasClass = event.target.classList.contains('box1'); console.log(hasClass); });

check if event target has class

We added a click event listener to the document object.

Every time we click on an element, a function is invoked.

We used the target property on the event object. The target property is a reference to the object (element) on which the event was dispatched.

In other words event.target gives us access to the DOM element the user clicked.

The classList.contains method allows us to check if an element's class list contains the provided class.

If the element has the class, the method returns true, otherwise false is returned.

Since the only element in the example that has the class of box1 is the first box, clicking on the element logs true to the console.

Clicking on any other element on the page logs false to the console.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.