語法
js
matches(selectors)
引數
返回值
如果 Element 匹配 selectors,則返回 true。否則,返回 false。
異常
SyntaxErrorDOMException-
如果
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!",因為該元素確實有一個值為 endangered 的 class 屬性。
規範
| 規範 |
|---|
| DOM # ref-for-dom-element-matches① |
瀏覽器相容性
載入中…
另見
- CSS 選擇器模組
- 其他接受選擇器的
Element方法:Element.querySelector()、Element.querySelectorAll()和element.closest()。