Javascript DOM HTML NamedNodeMap item() Method

Introduction

Get the name of the first attribute of a <button> element:

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

Click the button to get the name of the button element's first attribute.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.example {//from w  w w . j av a  2  s. co  m
  color: red;
  padding: 5px;
  width: 150px;
  font-size: 15px;
}
</style>
</head>
<body>

<button onclick="myFunction()" class="example">Test</button>
<p id="demo"></p>

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

</body>
</html>

The item() method returns the node at the specified index in a NamedNodeMap as a Node object.

The nodes are sorted as they appear in the source code and the index starts at 0.

There are two ways to access an attribute node at the specified index in a NamedNodeMap:

document.getElementsByTagName("BUTTON")[0].attributes.item(1);?? // The 2nd attribute
document.getElementsByTagName("BUTTON")[0].attributes[1];??????? // The 2nd attribute

In this example, the name of the first attribute is "onclick", and the second is "class".

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.example {/* w ww .  j  a va 2 s . com*/
  color: red;
  padding: 10px;
  width: 150px;
  font-size: 15px;
}
</style>
</head>
<body>

<button onclick="myFunction()" class="example">Test</button>
<p id="demo"></p>

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

</body>
</html>

Will produce the same result as this syntax:

View in separate window

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

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

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

</body>
</html>

We can use the length property to return the number of nodes in a NamedNodeMap object.

item(index);

Parameter Values

Parameter Type Description
index Number Required. The index of the node in the NamedNodeMap you want to return

The item() method returns a Node object representing the attribute node at the specified index.

The item() method returns null if the index number is out of range.




PreviousNext

Related