เอกสาร HTML DOM getElementsByClassName()
ตัวอย่าง
รับองค์ประกอบทั้งหมดที่มี class="example":
const collection = document.getElementsByClassName("example");
รับองค์ประกอบทั้งหมดที่มีทั้งคลาส "ตัวอย่าง" และ "สี":
const collection = document.getElementsByClassName("example color");
ตัวอย่างเพิ่มเติมด้านล่าง
ความหมายและการใช้งาน
วิธี การgetElementsByClassName()
ส่งคืนคอลเลกชันขององค์ประกอบที่มีชื่อคลาสที่ระบุ
getElementsByClassName()
วิธีการส่งคืนHTMLCollection
คุณสมบัติgetElementsByClassName()
เป็นแบบอ่านอย่างเดียว
HTMLCollection
HTMLCollection คือ ชุดของโหนด HTML
โหนดในคอลเล็กชันสามารถเข้าถึงได้ด้วยหมายเลขดัชนี ดัชนีเริ่มต้นที่ 0
คุณสมบัติความยาวส่งคืนจำนวนองค์ประกอบในคอลเลกชัน
ดูสิ่งนี้ด้วย:
เอกสาร getElementById() Method
เอกสาร getElementsByTagName() Method
ไวยากรณ์
document.getElementsByClassName(classname)
พารามิเตอร์
Parameter | Description |
classname | Required. The class name of the elements. Search for multiple class names separated by spaces like "test demo". |
คืนมูลค่า
พิมพ์ | คำอธิบาย |
วัตถุ. | วัตถุHTMLCollection _ คอลเลกชันขององค์ประกอบที่มีชื่อคลาสที่ระบุ องค์ประกอบจะถูกจัดเรียงตามที่ปรากฏในเอกสาร |
ตัวอย่างเพิ่มเติม
จำนวนองค์ประกอบที่มี class="example":
let numb = document.getElementsByClassName("example").length;
เปลี่ยนสีพื้นหลังขององค์ประกอบทั้งหมดด้วย class="example":
const collection = document.getElementsByClassName("example");
for (let i = 0; i < collection.length; i++) {
collection[i].style.backgroundColor = "red";
}
หน้าที่เกี่ยวข้อง
บทช่วยสอน CSS: ไวยากรณ์ CSS
การอ้างอิง CSS: CSS .class Selector
การอ้างอิง HTML DOM: องค์ประกอบ .getElementsByClassName()
การอ้างอิง HTML DOM: className Property
การอ้างอิง HTML DOM: คุณสมบัติ classList
การอ้างอิง HTML DOM: Style Object
รองรับเบราว์เซอร์
document.getElementsByClassName()
เป็นคุณลักษณะ DOM ระดับ 1 (1998)
ได้รับการสนับสนุนอย่างเต็มที่ในเบราว์เซอร์ทั้งหมด:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |