การจับคู่ HTML DOM ()วิธี การ
❮ วัตถุธาตุตัวอย่าง
กำหนดว่าองค์ประกอบตรงกับตัวเลือก CSS หรือไม่:
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";
}
ความหมายและการใช้งาน
เมธอดส่งคืน ค่าmatches()
บูลีนที่ระบุว่าองค์ประกอบตรงกับตัวเลือก CSS เฉพาะหรือไม่
เคล็ดลับ:สำหรับรายการ CSS Selectors ทั้งหมด โปรดดูที่CSS Selectors Referenceของเรา
รองรับเบราว์เซอร์
ตัวเลขในตารางระบุเบราว์เซอร์รุ่นแรกที่รองรับวิธีการนี้อย่างเต็มที่
Method | |||||
---|---|---|---|---|---|
matches() | 33.0 | 18.0 | 34.0 | 7.0 | 21.0 |
ไวยากรณ์
element.matches(selectors)
ค่าพารามิเตอร์
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. |
รายละเอียดทางเทคนิค
คืนมูลค่า: |
บูลีนที่ระบุว่าองค์ประกอบสามารถจับคู่โดยตัวเลือก CSS ได้หรือไม่:
|
---|
ตัวอย่างเพิ่มเติม
ตัวอย่าง
ค้นหาว่าองค์ประกอบตรงกับหนึ่งในตัวเลือกหลายตัวหรือไม่:
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.";
}
หน้าที่เกี่ยวข้อง
การอ้างอิง JavaScript: เมธอดelement.closest()
❮ วัตถุธาตุ