In this tutorial we will learn How to Get attribute Value using JavaScript. getAttribute() method can be used for this purpose which returns the attribute value of HTML element.
Table of Contents
getAttribute() method
getAttribute() method returns the value of the HTML attribute.
In this example we can use getAttribute() method to get value of attribute of div tag.
HTML Code
HTML Code is given below, in this code we have a div tag with two attributes defined and a button tag with onclick event.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Get Attribute Value</title>
<style>
.red
{
background-color: red;
margin: 10px 0px;
padding: 10px 5px;
}
</style>
</head>
<body>
<div id="mainDiv" class="red">This is main div.</div>
<button onclick="attributeValue()">Get Attribute Value</button>
<script src="script.js"></script>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code, In this code on click of a button, user defined function attributeValue() will get us the value of defined attribute.
In this example getAttribute() method is used to get value of class attribute.
You can use it to get value of any attribute. The name of attribute whose value is required is defined inside the getAttribute() method as a parameter.
<script>
function attributeValue()
{
var element = document.getElementById("mainDiv");
var value = element.getAttribute("class");
alert(value);
}
</script>
Demo
Video Tutorial
Watch video tutorial on how to Get attribute Value using JavaScript.