ADVERTISEMENT
ADVERTISEMENT

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.

Syntax:

$(selector).attr(attribute,value)

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", "http://www.google.com/")

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="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Example:

HTML Code:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Title</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
   </head>
   <body>
      <center>
         <h1><a id="link" href="https://www.wikipedia.com">Visit The Website...!!!</a></h1>
      </center>
   </body>
</html>

jQuery Function:

<script>
    $(document).ready(function(){
        $("#link").attr('href','https://www.google.com');
    });
</script>

Output:

Example: Change the href attribute


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

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

© https://www.includehelp.com some rights reserved.