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 2017年4月.
matches()
は Element
インターフェイスのメソッドで、この要素が指定した CSS セレクター によって選択されるかどうかを検査します。
構文
js
matches(selectors)
引数
返値
Element
が selectors
に一致すれば 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①> |
ブラウザーの互換性
Loading…
関連情報
- CSS セレクターモジュール
- セレクターを使用するその他のメソッド:
element.querySelector()
およびelement.closest()