How to add, remove and get attribute using Jquery

Learn how to efficiently set, remove and get attribute using Jquery.

Attributes gives extra power when working with DOM elements as they make them more flexible and it is easy to create deep structures.

Get attribute using Jquery

.attr('name') method can be used to retrieve the value of the given attribute from the element.

<div class="abc" width="500px" height="300px"></div>

//Get attribute value for 
//element with class abc
let val = $('.abc').attr('width');

console.log(val);
//500px

If the attribute does not exists then undefined will be returned.


Setting attribute using Jquery

We can use the same .attr() method to add or update the attribute.

Adding attribute

If the attribute does not exits already then it will create a new one.

<div class="abc" width="500px" height="300px"></div>

$('.abc').attr('prashant', 'randomValue');

<div class="abc" width="500px" height="300px" prashant="randomValue"></div>

Updating attribute

If the attribute already exists then it will update the value.

<div class="abc" width="500px" height="300px"></div>

$('.abc').attr('width', '600px');

<div class="abc" width="600px" height="300px"></div>

.attr(attr, function) method also takes a callback function as input instead of value through which we can set the value of the element.

$('.abc').attr('width', function(index, currentValue){
    return '600px';
});

<div class="abc" width="600px" height="300px"></div>

We can also set the multiple attributes together.

$('.abc').attr({'width': '600px', 'height': '700px'});

<div class="abc" width="600px" height="700px"></div>

Remove attribute using Jquery

We can use the removeAttr() method to remove the attribute from the DOM element.

<div class="abc" width="500px" height="300px"></div>

$('.abc').removeAttr('width');

<div class="abc" height="300px"></div>