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.
You want to ask "is this a disabled button?" without checking tagName and an attribute separately.
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)'));true
false
truematches(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.