ใช้ getElementsByClassName() วนลูปผูก Event Listener
ดึง element ทั้งหมดที่มี class ตรงกัน แล้ววนลูปเพิ่ม event listener ให้แต่ละตัว
ตัวอย่างโค้ดเต็ม
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Button Alert</title>
</head>
<body>
<button class="clickTheButton">Click The Button to get an alert</button>
<button class="clickTheButton">Another Button</button>
<script>
// ดึง element ทั้งหมดที่มี class นี้ (คืน HTMLCollection)
const buttons = document.getElementsByClassName("clickTheButton");
// วนลูปผูก event (ต้องแปลงเป็นอาร์เรย์ก่อน หรือใช้ for...of)
for (const btn of buttons) {
btn.addEventListener("click", alertMessage);
}
function alertMessage() {
alert("You have clicked the button");
}
</script>
</body>
</html>
วิธีรัน
บันทึกเป็น index.html แล้วเปิดด้วย Live Server
คำอธิบาย
getElementsByClassName()คืน HTMLCollection (live collection)- ใช้
for...ofวนลูปได้โดยตรง (ES6+) - หรือแปลงเป็นอาร์เรย์:
Array.from(buttons).forEach(...)
วิธีทันสมัย: Event Delegation (แนะนำ)
document.addEventListener('click', (e) => {
if (e.target.matches('.clickTheButton')) {
alert('You clicked!');
}
});
วิธีนี้จัดการปุ่มที่เพิ่มมาใหม่ได้อัตโนมัติ และประหยัด memory