The attributes property in HTML DOM returns the group of node attributes specified by NamedNodeMap objects. The NamedNodeMap object represents the collection of attribute objects and can be accessed by index number. The index number starts at 0.Â
Syntax
node.attributesReturn Value: It returns the NamedNodeMap object which is the collection of nodes.Â
Note: In Internet Explorer 8 and earlier versions, the attributes property will return a collection of all possible attributes for an element that can result in higher value than expected.Â
Example 1:Â
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>
HTML DOM attributes Property
</title>
</head>
<body>
<!-- Setting up an image -->
<img id = "GFG" src =
"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-logo.png" >
<br>
<!--Driver Code Ends-->
<button onclick = "myGeeks()">
DOM attributes property
</button>
<p id = "demo"></p>
<script>
function myGeeks() {
// It returns the number of nodes
var x = document.getElementById("GFG").attributes.length;
// Display the number of nodes
document.getElementById("demo").innerHTML = x;
}
</script>
<!--Driver Code Starts-->
</body>
</html>
<!--Driver Code Ends-->
Example 2:Â
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>
HTML DOM attributes Property
</title>
</head>
<body>
<h2>HTML DOM attributes Property</h2>
<button id="GFG" onclick="myGeeks()">
Click Here!
</button>
<br>
<br>
<span>Button element attributes:</span>
<span id="sudo"></span>
<!--Driver Code Ends-->
<script>
function myGeeks() {
// It returns the number of nodes
var gfg =
document.getElementById("GFG").attributes.length;
// Display the number of nodes
document.getElementById("sudo").innerHTML = gfg;
}
</script>
<!--Driver Code Starts-->
</body>
</html>
<!--Driver Code Ends-->
- element.attributes gives you a live collection of all the elementâs attribute nodes (Attr objects). Because it is a NamedNodeMap (not a regular array), it does not have Array methods such as map(), filter(), or forEach(). You can still iterate it with for...of or access items by index or by name.
- The order of attributes in the NamedNodeMap is not standardized and can differ between browsers. You should never rely on a specific order when looping through element.attributes. For a more modern and reliable approach when you only need the names, prefer element.getAttributeNames().