Element: matches() メソッド

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

matches()Element インターフェイスのメソッドで、この要素が指定した CSS セレクター によって選択されるかどうかを検査します。

構文

js
matches(selectors)

引数

selectors

Element を検査するために有効な CSS セレクターを格納した文字列です。

返値

Elementselectors に一致すれば true です。そうでなければ false です。

例外

SyntaxError DOMException

selectors が CSS のセレクターリストとして解釈できない場合に発生します。

HTML

html
<ul id="birds">
  <li>Orange-winged parrot</li>
  <li class="endangered">Philippine eagle</li>
  <li>Great white pelican</li>
</ul>

JavaScript

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

for (const bird of birds) {
  if (bird.matches(".endangered")) {
    console.log(`The ${bird.textContent} is endangered!`);
  }
}

要素が実際に値 endangered 持つ class 属性を持つので、これは、コンソールのログに "The Philippine eagle is endangered!" と表示されます。

仕様書

Specification
DOM
# ref-for-dom-element-matches①

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
matches

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Uses a non-standard name.
Has more compatibility info.

関連情報