ใช้ document.getElementsByClassName() คืนค่า HTMLCollection วนลูปด้วย Index แบบเดิม
ตัวอย่างโค้ด
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="demo">My First JavaScript Program</div>
<div class="demo">This is the second Program</div>
<div class="demo">This is the third Program</div>
<script>
var className = document.getElementsByClassName('demo');
for (var index = 0; index < className.length; index++) {
console.log(className[index].innerHTML);
}
</script>
</body>
</html>
วิธีรันโปรแกรม
- บันทึกไฟล์ชื่อ "anyName.html" หรือ "index.html"
- คลิกขวาที่ไฟล์ เลือก "Open with Live Server" ใน VS Code Editor
ผลลัพธ์
แสดงข้อความภายในทุก div class="demo" ใน Console