jQuery attr() Method

The jQuery attr() method is a versatile tool for manipulating attributes of HTML elements. It allows you to retrieve, modify, or set attribute values, enabling dynamic changes to elements' behavior and appearance. Here are examples illustrating the usage of the attr() method:

Getting Attribute Value

Consider an HTML anchor (<a>) element:

<a id="myLink" href="https://www.example.com">Visit Example</a>

To retrieve the value of the href attribute using jQuery:

var linkHref = $("#myLink").attr("href"); console.log(linkHref); // Output: "https://www.example.com"

Setting Attribute Value

You can use the attr() method to set or modify attribute values:

$("#myLink").attr("target", "_blank");

This will set the target attribute to "_blank," making the link open in a new tab.

Manipulating Multiple Attributes

The attr() method can also modify multiple attributes at once by passing an object with attribute-value pairs:

$("#myLink").attr({ "href": "https://newlink.com", "target": "_self" });

In this example, both the href and target attributes of the link will be updated.

Removing an Attribute

To remove an attribute, set its value to null:

$("#myLink").attr("target", null);

This will remove the target attribute from the link.

Working with Custom Attributes

The attr() method can also manage custom attributes:

<div id="myDiv" data-category="books">Books Category</div> var category = $("#myDiv").attr("data-category"); // Retrieves the value of "data-category" $("#myDiv").attr("data-category", "electronics"); // Sets "data-category

Workign Examples

jQuery Get Attribute

var alt = $("#imgID").attr("alt") alert(alt);
<img id="imgID" src="dummy.png" alt="Not set" />

jQuery Set Attribute

$("#imgID").attr("alt", "New Attribute..");
<img id="imgID" src="dummy.png" alt="Not set" />
run this source code Browser View

Not set
Full Source
<html> <head> <title>jQuery attr() example</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { $("#btnGet").click(function(){ var alt = $("#imgID").attr("alt") alert(alt); }); $("#btnSet").click(function(){ $("#imgID").attr("alt", "New Attribute.."); }); }); </script> </head> <body> <button id="btnGet">Get Val</button> <button id="btnSet">Set Val</button></br> <img id="imgID" src="dummy.png" alt="Not set" /> </body> </html>


The attr() method is a valuable tool for handling attributes, whether standard HTML attributes or custom ones. It's important to note that if you're dealing with properties like checked or disabled, it's often better to use the prop() method instead.