JavaScript cung cấp getAttributeNode() tìm attribute node theo tên của element, trả về attribute object. Nếu attribute không tồn tại, trả về null hoặc chuỗi rỗng.
Cú pháp
element.getAttributeNode(attributename);
Ví dụ
2 thẻ heading với class khác nhau. getAttributeNode() trả về attribute class. Hoạt động như array - dùng index để truy cập nhiều element.
<html> <body> <h2 class="class1">Tutorix</h2> <h2 class="class2">Tutorialspoint</h2> <p id = "attribute"></p> <script> var elmnt = document.getElementsByTagName("h2")[1]; var value = elmnt.getAttributeNode("class").value; document.getElementById("attribute").innerHTML = value; </script> </body> </html>
Kết quả
Tutorix Tutorialspoint class2
Thường dùng hơn: element.getAttribute('class') trả về trực tiếp giá trị string. getAttributeNode() trả về object Attr (có property name, value). Hiện đại: element.className hoặc element.classList.