Element.prototype.matches can be used to check if an element includes a certain class
- 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.
To figure out if an element contains a particular class is a quite common operation when building interfaces. Today I came across an article by David Gilbterson which describes "15 HTML element methods youโve potentially never heard of" and it introduced me to Element
. This 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
Edited: It turns out matches
also capable of dealing with several classes. (elem
โ "element matches
or
").
Related Topics
Related Articles
- How to create an API wrapper using a JavaScript proxy
- "fetch" supports a "keepAlive" option to make it outlive page navigations
- A clipboard magic trick - how to use different MIME types with the Clipboard API
- Keyboard button clicks with Space and Enter behave differently
- VS Code supports JSDoc-powered type checking