ใช้ document.querySelectorAll('[data-sentence]') เลือก Element ที่มี attribute data-sentence
ตัวอย่างโค้ด
<!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>
<p data-sentence="This is the program"></p>
<br/>
<h6 data-sentence="This is the test"></h6>
<script>
var result = document.querySelectorAll('[data-sentence]');
for (var index in result) {
if (result.hasOwnProperty(index)) {
console.log(result[index].getAttribute('data-sentence'));
}
}
</script>
</body>
</html>
วิธีรันโปรแกรม
- บันทึกไฟล์ชื่อ "anyName.html" หรือ "index.html"
- คลิกขวาที่ไฟล์ เลือก "Open with Live Server" ใน VS Code Editor
ผลลัพธ์
แสดงค่า attribute data-sentence ของทุก Element ใน Console