Skip to content
jshacks.dev
Browser

Check if an element matches a selector with matches

Test whether an element would be selected by a CSS selector with matches, instead of comparing class names or tag names by hand. Works in all modern browsers.

1 min read
Summarize in AI

You want to ask "is this a disabled button?" without checking tagName and an attribute separately.

matches.jsJavaScript
document.body.innerHTML = `
  <button id="save" class="primary" disabled>Save</button>
  <button id="cancel">Cancel</button>`;

const save = document.querySelector('#save');
const cancel = document.querySelector('#cancel');

console.log(save.matches('button.primary:disabled'));
console.log(cancel.matches('button.primary'));
console.log(cancel.matches(':not(.primary)'));
Text
true
false
true

matches(selector) returns true when the element would be selected by that selector if it were queried from the document. Any selector works: classes, attributes, :disabled, :not(). It is the same engine as querySelector, exposed as a yes/no question, and is defined in the DOM Standard.

The selector is evaluated against the whole document, so a selector with combinators, such as .list > button, depends on the element's place in the tree, not only on the element. Older code uses the prefixed webkitMatchesSelector, which every current browser has replaced with matches.

Share

More snippets

APIs

Send JSON with fetch POST

Send a JSON body with fetch POST by stringifying the object and setting the Content-Type header, since fetch does not do either of those for you.

1 min read
APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
Browser

Find the closest ancestor with closest

Walk up from an element to the nearest ancestor that matches a selector with closest, which includes the element itself. Works in all modern browsers.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.