Get attribute Value with JavaScript

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.

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.

How To Change Image Size with JavaScript How to change Image opacity with JavaScript How to Change image src on click with JavaScript How to get the lang attribute value in JavaScript How to Get attribute Value using JavaScript How To Check if Attribute Exists or not with JavaScript How To Count number of links on Page with JavaScript How To Scroll Page to Bottom using JavaScript How To Detect Shift Key Press with JavaScript Change Text Color On Hover with JavaScript Hide and Show div using JavaScript Get Button text with JavaScript Get textarea value with JavaScript Get table row Height with JavaScript Auto Increase width of input field with JavaScript Set Textarea maxLength with JavaScript Set Textarea Value with JavaScript JavaScript Count list items JavaScript set input field value Count Button Clicks with JavaScript Scroll Page to the Top on Click with JavaScript Change id of Element with JavaScript JavaScript Change li Text Color JavaScript Change li Text JavaScript Remove id from Element