The attributes property returns a collection of the specified node's attributes, as a NamedNodeMap object.
The nodes can be accessed by index numbers, and the index starts at 0.
Numerical indexing is useful for going through all of an element's attributes: You can use the length property of the NamedNodeMap object to determine the number of attributes, then you can loop through all attributes nodes and extract the info you want.
HTML attributes are attribute nodes, with all the properties and methods available for the Attribute object.
Syntax and Usage
node.attributes
<img id="Img" alt="Flower" src="../image/demo1.jpg" width="150" height="113">
<br>
<h2 id="demo1"></h2>
<button class="btn btn-primary" onclick="num_att()">Click it</button><br><br>
<script>
function num_att() {
var x = document.getElementById("Img").attributes.length;
document.getElementById("demo1").innerHTML = x;
}
</script>
<h2 id="demo2"></h2>
<br>
<button class="btn btn-primary" id="btn" onclick="count_att()">Click it</button><br><br>
<script>
function count_att() {
var x = document.getElementById("btn").attributes.length;
document.getElementById("demo2").innerHTML = x;
}
</script>
<!DOCTYPE html>
<html>
<head>
<title>HTML DOM Attributes Property With JavaScript</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<style>
h1 {
color: red;
}
</style>
<body>
<div class="container">
<br>
<br>
<div class="text-center">
<h1>HTML DOM Attributes Property With JavaScript</h1>
</div>
<br>
<div class="well">
<img id="Img" alt="Flower" src="../image/demo1.jpg" width="150" height="113">
<br>
<h2 id="demo1"></h2>
<br>
<h2 id="demo2"></h2>
<br>
<button class="btn btn-primary" onclick="num_att()">Click it</button><br><br>
<button class="btn btn-primary" id="btn" onclick="count_att()">Click it</button><br><br>
</div>
<br>
</div>
</body>
</html>
<script>
function num_att() {
var x = document.getElementById("Img").attributes.length;
document.getElementById("demo1").innerHTML = x;
}
function count_att() {
var x = document.getElementById("btn").attributes.length;
document.getElementById("demo2").innerHTML = x;
}
</script>