เพื่อได้ค่า HTML attribute ลองดังนี้:
$("#demo").attr("tabindex")
เมธอด attr() ใช้ดึงค่า attribute จาก element แรกใน matched set หรือตั้งค่า attribute ทุก matched elements
ยังใช้ hasAttribute() เช็คว่า element มี attribute นั้นหรือไม่
ตัวอย่าง
ลองรันโค้ดเรียนรู้ hasAttribute():
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('button').on('click', function() {
if (this.hasAttribute("style")) {
alert('True')
} else {
alert('False')
}
})
});
</script>
</head>
<body>
<button class='button' style='background-color:blue;'>Button</button>
<button class='button'>Button 2</button>
</body>
</html>