Element: matches() 方法

Baseline 已廣泛支援

該特性已非常成熟,可在多種裝置和瀏覽器版本上使用。自 2017 年 4 月以來,它已在各大瀏覽器上可用。

Element 介面的 matches() 方法用於測試該元素是否會匹配指定的 CSS 選擇器

語法

js
matches(selectors)

引數

選擇器 (selectors)

包含有效 CSS 選擇器 的字串,用於與 Element 進行匹配測試。

返回值

如果 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!`);
  }
}

這將會在控制檯輸出 "The Philippine eagle is endangered!",因為該元素確實有一個值為 endangeredclass 屬性。

規範

規範
DOM
# ref-for-dom-element-matches①

瀏覽器相容性

另見