Sử dụng document.querySelectorAll('[data-*]') để chọn tất cả element có attribute bắt đầu bằng "data-".
Ví dụ
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chọn data-* attribute</title>
</head>
<body>
<p data-sentence="This is the program"></p>
<br/>
<h6 data-sentence="This is the test"></h6>
<script>
var elements = document.querySelectorAll('[data-sentence]');
for (var i = 0; i < elements.length; i++) {
console.log(elements[i].getAttribute('data-sentence'));
}
</script>
</body>
</html>
Cách chạy
Lưu index.html, mở Live Server, xem console.
Kết quả console
This is the program
This is the test
Mở rộng: Dùng [data-*] để chọn tất cả attribute data- bất kỳ: document.querySelectorAll('[data-*]').