Last updated: Mar 5, 2024
Reading time·2 min
To check if event.target has a specific class, call the classList.contains()
method on the target
object.
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.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> <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.
document.addEventListener('click', function handleClick(event) { const hasClass = event.target.classList.contains('box1'); console.log(hasClass); if (hasClass) { console.log('Event.target has the specified class'); } else { console.log( 'Event.target does NOT have the specified 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.
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.
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.
matches()
You can also use the
Element.matches()
method to check if event.target
has a specific class.
document.addEventListener('click', function handleClick(event) { const hasClass = event.target.matches('.box1'); console.log(hasClass); if (hasClass) { console.log('Event.target has the specified class'); } else { console.log('Event.target does NOT have the specified class'); } });
The code sample checks if event.target
has a class of box1
.
The matches()
method of the Element
interface takes a selector and tests
whether the element would be selected by the provided selector.
Notice that we passed a selector to the method (.box1
) instead of the name of
the class.
You can learn more about the related topics by checking out the following tutorials: