Artboard 16light, inspiration, solution, idea, innovation,Google Sheets iconSwift icon
Published at
Updated at
Reading time
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.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 = 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.matches('.foo, .bar') โ€“ "element matches .foo or .bar").

Related Topics

Related Articles