JavaScript Reference ยท DOM: Document and Elements
Element.matches()
Reference for Element.matches(): check whether an element would be selected by a CSS selector, with filtering and event handling examples and edge cases.
The matches() method returns true if an element would be selected by a given CSS selector, and false otherwise. It is the inverse of querySelectorAll(): instead of asking "which elements match this selector?", you ask "does this element match?".
That makes it useful for filtering lists of elements, for checking an event target, and for testing states like :checked or :disabled with the same selector syntax you already use in CSS.
if (element.matches(".card:not(.hidden)")) { /* ... */ }
Try it
Syntax
element.matches(selectors)
| Name | Description |
|---|---|
selectors |
A string with a valid CSS selector list. The result is true if the element matches any selector in the list. |
Return value: a boolean.
Exceptions: SyntaxError (DOMException) if the selector is not valid.
Usage notes
- Matched against the whole document. A selector like
ul > liis true when the element's real parent is aul, even though you only passed one element. The selector is not scoped to the element's subtree. :scopeis the element itself. Inmatches(),:scoperefers to the element you call it on, soel.matches(":scope")istrue. It is mostly useful withquerySelector(), where it anchors a selector to the element.- Dynamic states work.
:hover,:focus,:checked,:disabled,:invalidand similar pseudo-classes reflect the current state. - Pseudo-elements never match.
::beforeand::afterare not elements, so selectors with them returnfalse. - Not for text nodes.
matches()exists onElementonly. Checknode instanceof Elementfirst when you work with generic nodes. - Older name. Old code and libraries use
webkitMatchesSelector()ormsMatchesSelector(). They are no longer needed. - Ancestor check. To ask whether any ancestor matches, use
closest().
Browser support
Supported in all current browsers.
Related
Element.closest()โ nearest matching ancestordocument.querySelector()โ find the first matchdocument.querySelectorAll()โ find all matches- Lesson: Selecting elements