How to use jQuery attr() to Get & Set Data Attribute Values

To set and get data on an HTML data to attribute in jQuery, use the attr() function.

 

Get Attribute Value

If you need to get the value of an attribute from an element, pass the name of the attribute like this:

 

<button id="button" type="button" data-color="blue">Blue button</button>
var color = $('#button').attr('data-color');

console.log(color);
blue

 

Set Attribute Value

To set the data attribute value, pass the value as the second argument of attr() like this:

 

<button id="button" type="button" data-color="blue">Blue button</button>
$('#button').attr('data-color', 'green');

var color = $('#button').attr('data-color');

console.log(color);
green
jquery