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 is given below, in this code we have a div tag with two attributes defined and a button tag with onclick event.

<!DOCTYPE html>
<title>JavaScript Get Attribute Value</title>
background-color: red;
margin: 10px 0px;
padding: 10px 5px;    
<div id="mainDiv" class="red">This is main div.</div> 
<button onclick="attributeValue()">Get Attribute Value</button>    
<script src="script.js"></script>    

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.

function attributeValue()
    var element = document.getElementById("mainDiv");
    var value = element.getAttribute("class");


Video Tutorial

Watch video tutorial on how to Get attribute Value using JavaScript.

Change font-size using JavaScript Get Font Size of any Tag using JavaScript Change Position of HTML Element using JavaScript How to Change Image on Hover with JavaScript How to Disable Button by Class Name in 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