Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
if (element.matches(".card:not(.hidden)")) { /* ... */ }

Try it

Filtering with matches()
State selectors and invalid input

Syntax

JavaScript
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 > li is true when the element's real parent is a ul, even though you only passed one element. The selector is not scoped to the element's subtree.
  • :scope is the element itself. In matches(), :scope refers to the element you call it on, so el.matches(":scope") is true. It is mostly useful with querySelector(), where it anchors a selector to the element.
  • Dynamic states work. :hover, :focus, :checked, :disabled, :invalid and similar pseudo-classes reflect the current state.
  • Pseudo-elements never match. ::before and ::after are not elements, so selectors with them return false.
  • Not for text nodes. matches() exists on Element only. Check node instanceof Element first when you work with generic nodes.
  • Older name. Old code and libraries use webkitMatchesSelector() or msMatchesSelector(). They are no longer needed.
  • Ancestor check. To ask whether any ancestor matches, use closest().

Browser support

Supported in all current browsers.