HTML DOM ที่ใกล้เคียงที่สุด ()วิธีการ
❮ วัตถุธาตุตัวอย่าง
ค้นหาองค์ประกอบที่ใกล้เคียงที่สุดที่ตรงกับตัวเลือก CSS และกำหนดเส้นขอบสีเหลือง:
var element = document.getElementById("myElement");
var closest =
element.closest(".container");
if (closest) {
closest.style.border = "10px solid yellow";
}
ความหมายและการใช้งาน
เมธอด จะclosest()
ค้นหาโครงสร้าง DOM เพื่อหาองค์ประกอบที่ใกล้เคียงที่สุดซึ่งตรงกับตัวเลือก CSS ที่ระบุ โดยเริ่มต้นที่องค์ประกอบ จากนั้นทดสอบระดับบนสุด ปู่ย่าตายาย และอื่นๆ จนกว่าจะพบรายการที่ตรงกัน หากไม่พบการจับคู่ เมธอดนี้จะคืนค่า
null
รองรับเบราว์เซอร์
ตัวเลขในตารางระบุเบราว์เซอร์รุ่นแรกที่รองรับวิธีการนี้อย่างเต็มที่
Method | |||||
---|---|---|---|---|---|
closest() | 41.0 | 15.0 | 35.0 | 6.0 | 28.0 |
ไวยากรณ์
element.closest(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. Tip: For a list of all CSS Selectors, look at our CSS Selectors Reference. |
รายละเอียดทางเทคนิค
คืนมูลค่า: |
องค์ประกอบระดับบนสุดหรือตัวองค์ประกอบเองที่ตรงกับตัวเลือก CSS ที่ระบุ หากไม่พบรายการที่ตรงกัน ค่า null จะถูกส่งกลับ ส่งข้อยกเว้น SYNTAX_ERR หากตัวเลือกที่ระบุไม่ถูกต้อง |
---|
หน้าที่เกี่ยวข้อง
การอ้างอิง JavaScript: เมธอดelement.matches()
❮ วัตถุธาตุ