HTML DOM đối sánh () Phương thức
❮ Đối tượng phần tửThí dụ
Xác định xem một phần tử có khớp với bộ chọn CSS hay không:
var element = document.getElementById("myElement");
if (element.matches(".container")) {
element.innerHTML = "This element matches the \".container\" CSS selector";
} else {
element.innerHTML = "This element does not match the \".container\" CSS selector";
}
Định nghĩa và Cách sử dụng
Phương matches()
thức trả về một giá trị Boolean cho biết liệu một phần tử có được khớp với một bộ chọn CSS cụ thể hay không.
Mẹo: Để biết danh sách tất cả các Bộ chọn CSS, hãy xem Tham khảo Bộ chọn CSS của chúng tôi .
Hỗ trợ trình duyệt
Các số trong bảng chỉ định phiên bản trình duyệt đầu tiên hỗ trợ đầy đủ phương pháp này.
Method | |||||
---|---|---|---|---|---|
matches() | 33.0 | 18.0 | 34.0 | 7.0 | 21.0 |
Cú pháp
element.matches(selectors)
Giá trị tham số
Parameter | Description |
---|---|
selectors |
Required. Specifies one or more CSS selectors to match the element. These are used to select HTML elements based on their id, classes, types, attributes, values of attributes, etc. For multiple selectors, separate each selector with a comma. The returned element depends on which element that is first found in the document (See "More Examples"). Tip: For a list of all CSS Selectors, look at our CSS Selectors Reference. |
Chi tiết kỹ thuật
Giá trị trả lại: |
Boolean, cho biết liệu công cụ chọn CSS có thể so khớp phần tử hay không:
|
---|
Các ví dụ khác
Thí dụ
Tìm hiểu xem một phần tử có khớp với một trong nhiều bộ chọn hay không:
var element = document.getElementById("myElement");
if (element.matches(".container, .wrapper")) {
element.innerHTML = "This element matches either the \".container\" CSS selector or the \".wrapper\" selector.";
} else {
element.innerHTML = "This element does not match any of the selectors.";
}
Các trang liên quan
Tham chiếu JavaScript: Phương thức element.closest () .
❮ Đối tượng phần tử