How to use attributes property for html element in Javascript

Access the attributes

You can obtain a collection containing all of the attributes. attributes property returns an array of Attr objects.

The properties of the Attr object are described in the following table.

PropertiesDescriptionReturns
nameReturns the name of the attributestring
valueGets or sets the value of the attributestring

Example


<!DOCTYPE HTML> 
<html> 
<body> 
 <p id="textblock" 
    class="Survey numbers" 
    data-Survey="apple" 
    data-sentiment="like"> 
     This is a test.<!--from   w  ww.ja v  a2 s. c om-->
 </p> 
 <script> 
     var elem = document.getElementById("textblock"); 
     var attrs = elem.attributes; 
     for (var i = 0; i < attrs.length; i++) { 
         document.writeln("Name: " + 
               attrs[i].name + 
               " Value: " + 
               attrs[i].value); 
     } 
     attrs["data-Survey"].value = "banana"; 
     document.writeln("Value of data-Survey attr: " + 
                attrs["data-Survey"].value); 
 </script> 
</body> 
</html>

Click to view the demo





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window