语法
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!`);
}
}
这将会在控制台输出 "The Philippine eagle is endangered!",因为该元素确实有一个值为 endangered
的 class
属性。
规范
规范 |
---|
DOM # ref-for-dom-element-matches① |
浏览器兼容性
加载中…
另见
- CSS 选择器模块
- 其他接受选择器的
Element
方法:Element.querySelector()
、Element.querySelectorAll()
和element.closest()
。