What is jQuery attr method?

Sometimes you need to change the attributes of elements in your web page upon user actions or some other reason. For example, changing the image dimensions, height, and width in the web page. Similarly, changing the paragraph, div properties, table borders, background color attributes etc. without reloading the web page.

A set attr example

Similarly, it may also be required to get elements attributes, like current image height or width, table width etc. on the basis of which you can perform some action, all without reloading the web page.

An example of Get attr

This is where jQuery attr works. The attr method is used to set or get/return element attributes in the document.

This tutorial will show you examples of setting different elements attributes on the fly but let us first look at the syntax of attr method.

How to use the jQuery attr method?

The syntax of attr to Set the value is:

$(“element”).attr(“property”,”value”);

The syntax to get attribute value is:

$(“element”).attr(“property”);

Where an element can be an image, a div, paragraph, table etc.

Note that, if you use attr jQuery method to set the attribute(s) of the element, it will change attributes to all matched elements. Whereas in the case of using it to return attribute value, it will return only the first matched element value.

jQuery set attr example to change image width attribute

The example below shows how to set the width of an image as you click on “change dimension” button by using attr in jQuery.

Experience this example online

jQuery set attribute example for image height and width

You can also set multiple attributes at one call with attr method. The example below shows how to set the width and height of an image as you click on the “change dimensions” button by using attr method.

Experience this example online

As you can see, you have to enclose multiple attributes in curly brackets and each property is followed by a colon while multiple properties are separated by commas.

jQuery set attr example with table attributes

The example below sets the table border as you click on “set table border” button by using $.attr method.

Experience this example online

A set attr example with div element

You can also set div element attributes by using attr method. The example below sets the text alignment of a div element to center as you click on the button.

Experience this example online

An example of getting attribute value

As mentioned in above section, you can use jQuery attr to get element attribute value as well. The example below returns the image height and width as you click on the button.

Experience this example online

 

Also see: jQuery CSS method |jQuery HTML method