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:
- attr() : to read, add, and change attributes
- removeAttr(): to remove attributes
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 .
The above code is a simple example which fetches title src of img tag
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.
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.
The method removeAttr() removes the specified attributes from the selected element.
The above code remove the title attribute using removeAttr() .