Element.prototype.matches
Tests whether the element would be selected by the specified CSS selector string
Syntax
element.matches(selectors)Parameters
| Parameter | Type | Description |
|---|---|---|
| selectors | string | A string containing CSS selectors to match against |
Return Value
true if the element matches the selectors, false otherwise
Examples
const el = document.querySelector('.item')!
console.log(el.matches('.item.active'))document.addEventListener('click', (e) => {
const target = e.target as HTMLElement
if (target.matches('button.delete')) {
target.closest('.card')?.remove()
}
})function filterBySelector(elements: Element[], selector: string) {
return elements.filter(el => el.matches(selector))
}Understanding Element.prototype.matches
The Element.prototype.matches method in JavaScript tests whether the element would be selected by the specified CSS selector string. It belongs to the Element object and is one of the most widely used methods for working with element values in modern JavaScript and TypeScript applications.
The method signature is element.matches(selectors). It accepts 1 parameter: selectors. When called, it returns true if the element matches the selectors, false otherwise. Understanding when and how to use matches() helps you write more expressive, readable code.
Common use cases for Element.prototype.matches include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like dom-closest, dom-queryselector, dom-queryselectorall, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for Element.prototype.matches is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
Element.prototype.closestTraverses the element and its parents toward the document root until it finds an element that matches the specified CSS selector
document.querySelectorReturns the first Element within the document that matches the specified CSS selector, or null if no matches are found
document.querySelectorAllReturns a static NodeList representing a list of the document's elements that match the specified group of CSS selectors
More Element Methods
Other methods in the Element object
Related Tools
More Element Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.