Element: matches() method
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2017.
Thuộc tính matches() của giao diện Element tests whether the element would be selected by the specified CSS selector.
Cú pháp
js
matches(selectors)
Tham số
selectors-
Một chuỗi chứa valid CSS selectors to test the
Elementagainst.
Giá trị trả về
true if the Element matches the selectors. Otherwise, false.
Ngoại lệ
SyntaxErrorDOMException-
Thrown if
selectorscannot be parsed as a CSS selector list.
Ví dụ
>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!`);
}
}
This will log "The Philippine eagle is endangered!" to the console, since the element
has indeed a class attribute with value endangered.
Đặc tả kỹ thuật
| Thông số kỹ thuật |
|---|
| DOM> # ref-for-dom-element-matches①> |
Trình duyệt hỗ trợ
Xem thêm
- CSS selectors module
- Other
Elementmethods that take selectors:Element.querySelector(),Element.querySelectorAll(), andelement.closest().