How to change the value of an attribute using jQuery?

The jQuery attr() method is used to get the value of an attribute. It can also be used to change the value of an attribute by providing a new value as the second parameter. In the example below, we will change the attribute value from tutorialspoint.com to tutorialspoint.com/java.

The syntax for changing an attribute value is: $(selector).attr(attributeName, newValue)

You can try to run the following code to learn how to change the value of an attribute using jQuery ?

Example

<html>
   <head>
      <title>Selector Example</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function(){
            $("button").click(function(){
               $("#tpoint").attr("href", "https://www.tutorialspoint.com/java");
            });
         });
      </script>
   </head>
   <body>
      <p><a href="https://www.tutorialspoint.com" id="tpoint">tutorialspoint.com</a></p>
      <button>Change attribute value</button>
      <p>The value of above link will change on clicking the above button. Check before and after clicking the link.</p>
   </body>
</html>

In this example, when the button is clicked, the href attribute of the link with id tpoint changes from "https://www.tutorialspoint.com" to "https://www.tutorialspoint.com/java". You can verify this by right-clicking on the link and inspecting the element before and after clicking the button.

Conclusion

The jQuery attr() method provides a simple way to dynamically change attribute values of HTML elements. This is particularly useful for updating links, image sources, or any other HTML attributes based on user interactions.

Updated on: 2026-03-13T17:48:07+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements