Course Content
AJAX and jQuery Plugins
Learn how to use AJAX and plugins with jQuery to create dynamic and interactive web applications.
0/3
JQuery
About Lesson

Working with Attributes in jQuery

In this lesson, you will learn how to work with HTML attributes using jQuery. We’ll cover how to get, set, and remove attributes efficiently using jQuery methods.

The .attr() method is used to get or set the value of an attribute for selected elements.

Get Attribute Value

To retrieve the value of an attribute:

JavaScript
const href = $("#link").attr("href");
console.log(href); // Logs the href attribute of the #link element

Set Attribute Value

To set a new value for an attribute:

JavaScript
$("#link").attr("href", "https://example.com"); // Sets the href attribute

The .removeAttr() method is used to remove an attribute from an element.

Remove Attribute

To remove an attribute from an element:

JavaScript
$("#link").removeAttr("target"); // Removes the target attribute

Set Attribute Value

To set a new value for an attribute:

JavaScript
$("#link").attr("href", "https://example.com"); // Sets the href attribute
JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Working with jQuery Attributes</title>
</head>
<body>
  <a href="#" id="link" target="_blank">Visit Example</a>

  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
  <script>
    $(document).ready(function() {
      // Set the href attribute
      $("#link").attr("href", "https://example.com");
      
      // Get the href attribute value
      const hrefValue = $("#link").attr("href");
      console.log("Current href value: " + hrefValue);

      // Remove the target attribute
      $("#link").removeAttr("target");
    });
  </script>
</body>
</html>