DEV Community

loading...

TIL: Element.prototype.matches can be used to check if an element includes a certain class

stefanjudis profile image Stefan Judis Originally published at stefanjudis.com on ・1 min read

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.prototype.matches. This element method can be used to check if an element includes a certain class and is way shorter than element.classList.contains. πŸŽ‰

const elem = querySelector('.foo');

elem.classList.contains('bar'); // true
elem.matches('.bar');           // true
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

pic
Editor guide
Collapse
ewbi profile image
ewbi

Just be careful in IE v9-11 where it is prefixed with "ms" (and uses the complete old name msMatchesSelector in v9):

caniuse.com/#feat=matchesselector

developer.mozilla.org/en-US/docs/W...