Check if an element includes a certain class with "matches"
Written by Stefan Judis
- Published at
- Updated at
- Reading time
- 1min
This post is part of my Today I learned series in which I share all my web development learnings.
A common operation when building interfaces is to figure out if an element contains a particular class. Today I learned about Element
. The element method can be used to check if an element includes a certain class and is way shorter than element
. ๐
const elem = document.querySelector('.foo');
elem.classList.contains('bar'); // true
elem.matches('.bar'); // true
It turns out matches can also deal with a selector that includes multiple classes. elem
returns true for elements with the class
or
. ๐
If you enjoyed this article...
Join 5.5k readers and learn something new every week with Web Weekly.
Reply to this post and share your thoughts via good old email.