Javascript DOM HTML NamedNodeMap length Property

Introduction

Get the number of attributes of a <button> element:

var x = document.getElementsByTagName("BUTTON")[0].attributes.length;

Click the button to see how many attributes the button element has:

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 onclick="myFunction()" class="example">Test</button>

<p>The result should be 2 (the button element's onclick and class attribute).</p>

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

<script>
function myFunction() {
  var x = document.getElementsByTagName("BUTTON")[0].attributes.length;
  document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The length property returns the number of nodes in a NamedNodeMap object.

A Node object's attributes is an example of a NamedNodeMap object.

This property is read-only.

We can use the item() method to return a node at the specified index in a NamedNodeMap object.

The length property returns a Number representing the number of attribute nodes in the nodemap.




PreviousNext

Related