HTML DOM attributes Property


The HTML DOM attributes property associated with attributes within a HTML tag returns a collection of a given node’s attributes in the form of an object of type NamedNodeMap. To access these nodes we can use the index numbers. The indexing starts from 0.

Syntax

Following is the syntax for HTML DOM attributes property −

node.attributes

Example

Let us see an example of attributes property −

 Live Demo

<!DOCTYPE html>
<html>
<body>
<p>Click the button the second attribute of the below list</p>
<button id="Btn" onclick="attributeFunc()">ATTR NAME</button>
<button id="Btn" onclick="attrLength()">ATTR LENGTH</button>
<ol id="LIST" type="A" start="5" reversed>
<li>ONE</li>
<li>TWO</li>
<li>THREE</li>
</ol>
<p id="SAMPLE"></p>
<script>
   function attributeFunc() {
      var x = document.getElementById("LIST").attributes[2].name;
      document.getElementById("SAMPLE").innerHTML = x;
   }
   function attrLength(){
      var x = document.getElementById("LIST").attributes.length;
      document.getElementById("SAMPLE").innerHTML = x;
   }
</script>
</body>
</html>

Output

This will produce the following output −

After clicking on ATTR NAME button −

After clicking on ATTR LENGTH button −

In the above example −

We first created an ordered list with attributes id, type and reversed attribute .

<ol id="LIST" type="A" start="5" reversed>
<li>ONE</li>
<li>TWO</li>
<li>THREE</li>
</ol>

We then created two buttons ATTR NAME and ATTR LENGTH to execute functions attributeFunc() and attrLength() respectively.

<button id="Btn" onclick="attributeFunc()">ATTR NAME</button>
<button id="Btn" onclick="attrLength()">ATTR LENGTH</button>

The attributeFunc() function gets the element with id “LIST” associated with it and gets its 2nd attribute name with attributes.name property. The attribute name at 2nd index is then displayed in the paragraph with id “Sample” −

function attributeFunc() {
   var x = document.getElementById("LIST").attributes[2].name;
   document.getElementById("SAMPLE").innerHTML = x;
}

The attrLenght() function also gets the element with id “LIST” associated with it and gets the number of attributes that specific element has using attributes.length, which returns 4 in our case. The value 4 is then displayed in the paragraph with id SAMPLE −

function attrLength(){
   var x = document.getElementById("LIST").attributes.length;
   document.getElementById("SAMPLE").innerHTML = x;
}

Updated on: 20-Feb-2021

85 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements