How to add attribute by attr jQuery method

How to add attributes in jQuery

You can add the attributes to specified elements of your web page by using jQuery attr method. For example, you can add a border to an HTML table that was created without a border at first. Similarly, setting/adding alignment to div text. Also adding height or width attribute to image element and so on.

An example of attr method

This tutorials shows how to add attributes to your web page’s elements by using attr method, but let us first see the syntax.

Syntax of jQuery attr to add attribute

The syntax of attr to set or add attribute is:

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

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

Note that, if you use attr method to set the attribute(s) of the element, it will change attributes of all matched elements.

jQuery add attribute example to change image width

The example below shows how to add width attribute to an image as you click on “change dimension” button by using attr method.

Experience this example online



Adding multiple attributes by attr method example

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

Experience this example online



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

Also see jQuery CSS | jQuery remove attribute | jQuery HTML

Was this article helpful?

Related Articles

Leave A Comment?