I’ve written a couple of posts recently about event delegation and guard clauses. There are many ways you can check the
event.target when using event delegation: by its ID, by its classes, by its tag name, by its attributes, and more. But the easiest way is to use the
matches() method is analogous to the
is() method in jQuery. You pass in any valid CSS selector and then the method will return
Given the following HTML element:
Assume we have already selected the element and saved it to the
heading variable. Here are some examples of the
Usage in an event listener
I’ll use the same example from my posts about event delegation and guard clauses. This time, though, I’ll use the
Given the following HTML, imagine that when one of the three paragraphs is clicked, I want to log its
textContent to the console:
In the following snippet, you can see the
matches() method in action. I used it within the
Notice that I’m using the logical NOT operator (
!) here, because I want to check if the element is NOT a paragraph:
It’s important to note that the
matches() method is implemented with vendor prefixes in a handful of browsers.
For consistent behaviour, you should either include the polyfill in your codebase or polyfill your site automatically using a service like polyfill.io.
Check out the following resources to learn more about the
If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!