Code has been added to clipboard!

Getting and Setting Attribute Values With jQuery .attr()

Reading time 1 min
Published Jan 18, 2018
Updated Sep 27, 2019

jQuery attr: Main Tips

  • The jQuery .attr() method sets or returns the values of the specified attributes of the selected elements.
  • For attributes that haven't been set, this method will return undefined.
  • To get or set properties of elements, use prop().

All the Ways of Using attr

The jQuery .attr() method can both set and return the values of the specified element attributes. To make jQuery set attribute value, follow this syntax:

$(selector).attr(attributeName, newValue);

In the example below, we set the height attribute's value to 200:

Example
$("button").click(() => {
    $("img").attr("height","200");
});

Note: instead of naming newValue to make jQuery set attribute value, you can define a function that returns the value needed.

It is also possible to modify multiple attributes using jQuery .attr():

$(selector).attr({attributeName:newValue, attributeName:newValue, ...});

By skipping the newValue parameter, you make jQuery get attribute value:

$(selector).attr(attributeName);

Latest Udacity Coupon Found:

Verified STAFF PICK

75% OFF COURSES

Udacity Black Friday Offer

The best time to save on Udacity courses is now - follow this coupon to access a 75% Udacity Black Friday discount & enjoy learning at a very low cost!

Expiration date: 28/01/2021
3176 People Used
Only 97 Left
Rating
5.0