How to change the href attribute for a hyperlink using jQuery?

In this tutorial, let's see that how can we change the href attribute for a hyperlink using jQuery?
Submitted by Pratishtha Saxena, on June 17, 2022

jQuery is a JavaScript library. It makes things like HTML document traversal and manipulation, and event handling, much simpler with an easy-to-use API.

For changing the href attribute for the hyperlink we'll use the Attribute Method of jQuery. This method, attr(), is used to get and set the values of the specified attribute.



Here, the selector is the HTML element. Attribute, will be href and value will be the specified value that you want to set.

Now, for example:

$("a").attr("href", "")

This is a jQuery code that will change the attribute href of the anchor tag here. But this will be applied to every anchor tag in the HTML document. Even if there are some anchor tags that don't have the href as its attribute, then this jQuery code will set the href attribute to those anchor tags, which is not what we want.

So, to be specific on what element has to be targeted, the id of the element will be specified.

Note: Always remember to apply the CDN link while working with jQuery.

<script src=""></script>


HTML Code:

<!DOCTYPE html>
<html lang="en">
      <meta charset="UTF-8">
      <script src=""></script>
         <h1><a id="link" href="">Visit The Website...!!!</a></h1>

jQuery Function:



Example: Change the href attribute


Comments and Discussions!


Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.