jQuery attr() Method

Attributes are the name/value pairs that you assign to elements in their start tags. The most basic components we can manipulate using jQuery is through the attributes and properties of the HTML DOM elements . The attributes are available through its node properties.


jQuery allows us to get, set or remove any attribute within an element. To do these things, you use the following methods:

  1. attr() : to read, add, and change attributes
  2. removeAttr(): to remove attributes

jQuery attr()

The attr() method can be used to either fetch the value of an attribute from the first element in the matched set or set attribute values onto all matched elements .

Get Attribute

The above code is a simple example which fetches title src of img tag

Set Attribute

The attr(name, value) method can be used to set the named attribute onto all elements in the wrapped set using the pass value. This will set all elements with the named attribute using the value passed by the method.

The above code is a simple example which set border attribute to an image tag.

run this source code Try it Yourself
My Photo

Full Source

The above code is first fetch the src attribute from img tag and set border attribute to the same img tag.

Setting multiple attributes

Setting multiple attributes is done the same was as setting a single attribute, but instead of passing a name and value as the two parameters to the attr() function, pass an associative array containing the attribute names and values and key-value pairs .

The above code is change the multiple attributes (img, title, alt) if img element.

run this source code Try it Yourself
My Photo

Full Source

Remove attribute

The method removeAttr() removes the specified attributes from the selected element.

The above code remove the title attribute using removeAttr() .
 (C) 2021    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About