One handy JavaScript technique is to add, say, a click event listener to a parent or ancestor element because you want the event to fire when the user clicks a child or descendant of the element. This is known as event bubbling, because a click (in this case) on a lower-level DOM descendant element “bubbles up” to a higher-level DOM ancestor element. In your handler function, if you passed the event
object as an argument, you can use event.target
to know which element was clicked.
However, it’s one thing to know which element was clicked, and it’s another to know whether a particular element was clicked. What do I mean by “particular”? I'm talking about an element that matches a specified selector. This is no big deal if you’re looking for, say, a certain id
value or a specified class
. In those cases, you could set up an if
statement to check event.target.id
or event.target.classList
. But what if you want to use, say, a descendant selector or a pseudo-class selector such as first-of-type
?
That sounds hard, but JavaScript offers a straightforward way to target any selector via its matches()
method:
element.matches(selector)
element
selector
The matches()
method returns true
if element
would be selected by selector
, and it returns false
, otherwise. Here’s an example:
Browser support: % (Source: caniuse.com)
Specification: