Published at
Updated at
Reading time
1min

A common operation when building interfaces is to figure out if an element contains a particular class. Today I learned about Element.prototype.matches. The element method can be used to check if an element includes a certain class and is way shorter than element.classList.contains. ๐ŸŽ‰

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.matches('.foo, .bar') returns true for elements with the class .foo or .bar. ๐Ÿ‘

If you enjoyed this article...

Join 6.3k readers and learn something new every week with Web Weekly.

Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles