Javascript DOM HTML NamedNodeMap length Property loop through all attributes

Introduction

Loop through all attributes of a <button> element and output the name of each attribute:

Click the button to get all attribute names of the button element.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.example {//from   w  w  w  .  j a  v a 2  s . c o  m
  color: red;
  padding: 5px;
  width: 150px;
  font-size: 15px;
}
</style>
</head>
<body>
<button id="myBtn" onclick="myFunction()" class="example">Test</button>

<p id="demo"></p>

<script>
function myFunction() {
  var txt = "";
  var x = document.getElementById("myBtn").attributes;

  var i;
  for (i = 0; i < x.length; i++) {
    txt += "Attribute name: " + x[i].name + "<br>";
  }
  document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>



PreviousNext

Related