attributes property in javascript
attributes property is used to return all the attributes present in a particular element.
In Javascript using attributes property, attributes and there values of an element can be accessed.
Syntax
var variable = element.attributes;
Example Explanation
- In the above example we have created a button (Know my attribute count).
- In the button we have set five attributes (type, id, value, class, onclick).
- When the button is clicked, a Javascript function (click_func()) is called.
- In the Javascript click_func function, first we are getting the element (document.getElementById("idBtn")) and storing in elem variable.
- In next line using the variable elem, we are getting the attributes of the button (elem.attributes) and storing in attr variable.
- And finally we are finding the total number of attributes present using length property, and displaying it (alert(attr.length)).
Example Explanation
- In the above example we have created a button (Know my class value).
- In the button we have set five attributes (type, id, value, class, onclick).
- When the button is clicked, a Javascript function (click_func()) is called.
- In the Javascript click_func function, first we are getting the element (document.getElementById("idBtn")) and storing in elem variable.
- In next line using the variable elem, we are getting the attributes of the button (elem.attributes) and storing in attr variable.
- And then to get the class value, using the .class property, we are getting the class object, and by using the .value property we are getting the value of the class and displaying it (alert(attr.class.value)).
Example Explanation
- In the above example we have created a button (Know all my attributes value).
- In the button we have set five attributes (type, id, value, class, onclick).
- When the button is clicked, a Javascript function (click_func()) is called.
- In the click_func Javascript function, first we are getting the element (document.getElementById("idBtn")) and storing in elem variable.
- In next line using the variable elem, we are getting the attributes of the button (elem.attributes) and storing in attr variable.
- Next a for loop is created, in it we are accessing each attributes present in the element. We have set the starting value i as 0 (i=0) and the loop must break when i value is greater than or equal to the total number of attributes.
- To access the name of the attribute .name property is used (attr[i].name) and to access the value of the attribute .value property is used, and both the values are displayed in the div container (result.innerHTML += attr[i].name + "=" + attr[i].value + "<br>";).