JavaScript Element matches() Method

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline
Instance method

What You’ll Learn

Element.matches() is an instance method that tests whether the element would be selected by a CSS selector string. It returns true or false—perfect for filtering lists, conditional styling logic, and loops. Learn the MDN birds example, comparison with closest(), and five try-it labs aligned with MDN.

01

Kind

Instance method

02

Tests

Current element

03

Arg

CSS selector string

04

Returns

true / false

05

Throws

SyntaxError

06

Status

Baseline widely

Introduction

When you loop through a list of elements, you often need a quick yes/no answer: “Does this node match my CSS rule?” Before matches(), developers checked className strings or wrote custom attribute tests.

matches(selectors) delegates that work to the browser’s CSS engine. Pass any valid selector—class, tag, ID, attribute, or pseudo-class—and get a boolean back. MDN: the method tests whether the element would be selected by the specified CSS selector.

💡
Beginner tip

matches() only checks the current element. To find a matching ancestor, use closest() instead.

This page is part of JavaScript Element. Related selector APIs include closest() and getElementsByClassName().

Understanding the matches() Method

Calling el.matches(selectors) asks the browser whether el would match if you ran that selector against the document.

  • It is an instance method on Element.
  • Tests only the element you call it on—no ancestor walk (MDN).
  • Returns true if the element matches, otherwise false (MDN).
  • Accepts the same selector strings as querySelector and querySelectorAll.
  • Throws SyntaxError if selectors is not valid CSS (MDN).
  • Formerly known as matchesSelector() in older drafts; also had vendor prefixes (webkitMatchesSelector, etc.).

📝 Syntax

General form of Element.matches (MDN):

JavaScript
matches(selectors)

Parameters

NameTypeDescription
selectorsStringA string containing valid CSS selectors to test the element against (MDN).

Return value

TypeDescription
Booleantrue if the element matches the selectors; otherwise false (MDN).

Exceptions

  • SyntaxError DOMException — thrown if selectors cannot be parsed as a valid CSS selector list (MDN).

Common patterns

JavaScript
// MDN birds example
for (const bird of document.querySelectorAll("li")) {
  if (bird.matches(".endangered")) {
    console.log(`The ${bird.textContent} is endangered!`);
  }
}

// Class check
if (card.matches(".active")) { /* ... */ }

// Compound selector
if (btn.matches("button.primary:enabled")) { /* ... */ }

// Attribute selector
if (link.matches("[href^='https']")) { /* ... */ }

⚡ Quick Reference

GoalCode
Test class on elementel.matches(".active")
Test tag nameel.matches("li")
Compound selectorel.matches("li.endangered")
Filter in a loopif (item.matches(sel)) { ... }
No matchfalse
MDN statusBaseline Widely available (since April 2017)

🔍 At a Glance

Four facts to remember about Element.matches().

Returns
boolean

true or false

Baseline
widely

Since April 2017

Scope
self

Current element only

Input
CSS

Selector string

📋 matches() vs closest() vs classList.contains()

el.matches(sel)el.closest(sel)el.classList.contains("x")
ScopeCurrent element onlySelf + ancestorsSingle class token
Return valuetrue / falseElement or nulltrue / false
Selector powerFull CSS selectorsFull CSS selectorsClass name only
Loop filteringIdealOverkillLimited
Best forTest current nodeFind nearest containerSimple class check

Examples Gallery

Examples follow MDN Element.matches() patterns. Use View Output or Try It Yourself for each case.

📚 Getting Started

MDN’s endangered birds list—filter with matches().

Example 1 — Endangered Birds (MDN)

Loop list items and log only those matching .endangered.

JavaScript
const birds = document.querySelectorAll("li");

for (const bird of birds) {
  if (bird.matches(".endangered")) {
    console.log(`The ${bird.textContent} is endangered!`);
  }
}
// "The Philippine eagle is endangered!"
Try It Yourself

How It Works

MDN: each li is tested individually. Only the Philippine eagle has class="endangered", so only that item logs a message.

Example 2 — Class Selector

Check whether a card element has the active class.

JavaScript
const card = document.querySelector(".card");

console.log(card.matches(".active"));  // false
card.classList.add("active");
console.log(card.matches(".active"));  // true
Try It Yourself

How It Works

matches(".active") returns true only when the element would be selected by that class selector. For a single class, it works like classList.contains("active") but accepts full CSS syntax.

📈 Practical Patterns

Compound selectors, pseudo-classes, and batch filtering.

Example 3 — Compound Selector

Test tag and class together: li.endangered.

JavaScript
const item = document.querySelector("li.endangered");

console.log(item.matches("li"));           // true
console.log(item.matches("li.endangered")); // true
console.log(item.matches("div"));         // false
Try It Yourself

How It Works

Compound selectors combine type and class. The element must satisfy all parts of the selector to return true.

Example 4 — :not() Pseudo-class

Test whether an element is not a div.

JavaScript
const li = document.querySelector("li");
const div = document.querySelector("div");

console.log(li.matches(":not(div)"));  // true
console.log(div.matches(":not(div)")); // false
Try It Yourself

How It Works

matches() supports the same pseudo-classes as CSS. :not(div) returns true for any element that is not a div.

Example 5 — Filter a NodeList

Collect only buttons that match button:not([disabled]).

JavaScript
const buttons = document.querySelectorAll("button");
const enabled = [];

for (const btn of buttons) {
  if (btn.matches("button:not([disabled])")) {
    enabled.push(btn.textContent);
  }
}

console.log(enabled.join(", "));
// "Save, Cancel"
Try It Yourself

How It Works

A common pattern: query broadly, then use matches() to narrow results with expressive CSS selectors instead of multiple property checks.

🚀 Common Use Cases

  • Filtering a NodeList or array of elements in a loop (MDN birds example).
  • Conditional logic based on CSS classes, tags, or attributes.
  • Validating form controls: input.matches(":invalid").
  • Checking button state: btn.matches(":enabled").
  • Feature-detecting styled components: el.matches("[data-theme='dark']").
  • Replacing manual className string checks with full CSS selectors.

🧠 How matches() Tests a Selector

1

Call on an element

el.matches(selectors) — pass a CSS selector string (MDN).

Start
2

Parse the selector

Browser validates the CSS. Invalid selectors throw SyntaxError (MDN).

Parse
3

Test current element

The engine checks whether el alone would match — no ancestor walk.

Match?
4

Return true or false

true if the element matches; false otherwise (MDN).

📝 Notes

  • Not Deprecated, Experimental, or Non-standard on MDN (Baseline Widely available, April 2017).
  • Returns a boolean — never null (unlike closest()).
  • Invalid selectors throw SyntaxError—validate dynamic selectors carefully.
  • Tests only the current element; use closest() to search ancestors.
  • Related selector APIs: querySelector(), querySelectorAll(), closest() (MDN).
  • Related: closest(), getElementsByClassName(), insertAdjacentText(), JavaScript hub.

Browser Support

Element.matches() is Baseline Widely available (MDN: across browsers since April 2017). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Element.matches()

Test whether an element matches a CSS selector — returns true or false.

Baseline Widely available
Google Chrome Supported · Desktop & Mobile
Yes
Microsoft Edge Supported · Chromium
Yes
Mozilla Firefox Supported · Desktop & Mobile
Yes
Apple Safari Supported · macOS & iOS
Yes
Opera Supported · Modern versions
Yes
Internet Explorer 9+ · Unprefixed in IE9+
Yes
matches() Excellent

Bottom line: Use matches() to test the current element against any CSS selector. Pair with loops for filtering, and use closest() when you need ancestors.

Conclusion

Element.matches() is the standard way to ask “does this element match my CSS selector?” It returns true or false, making it ideal for loops, filters, and conditional UI logic.

Continue with closest(), insertAdjacentText(), shadowRoot, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use in loops to filter querySelectorAll results (MDN)
  • Prefer expressive CSS over manual property checks
  • Use classList.contains() for a single class; matches() for complex selectors
  • Combine with pseudo-classes: :enabled, :invalid, :not()
  • Wrap dynamic selectors in try/catch if user-provided

❌ Don’t

  • Use matches() when you need an ancestor (use closest)
  • Build selectors from unescaped user input
  • Expect it to search child elements
  • Confuse return value with an Element reference
  • Rely on vendor-prefixed aliases in new code

Key Takeaways

Knowledge Unlocked

Five things to remember about Element.matches()

Boolean CSS selector tests on the current element.

5
Core concepts
📄 02

Scope

self only

Element
✍️ 03

Arg

CSS selector

Input
04

Baseline

widely available

Status
05

Pattern

loop filter

MDN

❓ Frequently Asked Questions

It tests whether the element would be selected by the given CSS selector string (MDN). It returns true if the element matches, otherwise false.
No. MDN marks Element.matches() as Baseline Widely available (across browsers since April 2017). It is not Deprecated, Experimental, or Non-standard.
A boolean: true if the element matches the selectors, false if it does not (MDN).
matches() tests only the current element. closest() walks up through ancestors (including self) and returns the first matching Element or null.
Yes. matches() accepts the same valid CSS selector strings as querySelector and querySelectorAll (MDN).
A SyntaxError DOMException is thrown if selectors cannot be parsed as a valid CSS selector list (MDN).
Did you know?

MDN’s birds example shows why matches() shines in loops: you can express “is this an endangered bird?” as bird.matches(".endangered") instead of parsing className manually.

More Element Topics

Browse Element methods and properties to keep building your DOM skills.

moveBefore() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful