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.
Properties | Description | Returns |
---|---|---|
name | Returns the name of the attribute | string |
value | Gets or sets the value of the attribute | string |
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>