Skip to content
Fix Code Error

How to change the href for a hyperlink using jQuery

March 13, 2021 by Code Error
Posted By: brian

How can you change the href for a hyperlink using jQuery?

Solution

Using

$("a").attr("href", "http://www.google.com/")

will modify the href of all hyperlinks to point to Google. You probably want a somewhat more refined selector though. For instance, if you have a mix of link source (hyperlink) and link target (a.k.a. “anchor”) anchor tags:

<a name="MyLinks"></a>
<a href="http://www.codeproject.com/">The CodeProject</a>

…Then you probably don’t want to accidentally add href attributes to them. For safety then, we can specify that our selector will only match <a> tags with an existing href attribute:

$("a[href]") //...

Of course, you’ll probably have something more interesting in mind. If you want to match an anchor with a specific existing href, you might use something like this:

$("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/')

This will find links where the href exactly matches the string http://www.google.com/. A more involved task might be matching, then updating only part of the href:

$("a[href^='http://stackoverflow.com']")
   .each(function()
   { 
      this.href = this.href.replace(/^http://beta.stackoverflow.com/, 
         "http://stackoverflow.com");
   });

The first part selects only links where the href starts with http://stackoverflow.com. Then, a function is defined that uses a simple regular expression to replace this part of the URL with a new one. Note the flexibility this gives you – any sort of modification to the link could be done here.

Answered By: Shog9

Related Articles

  • Reference - What does this regex mean?
  • How to set HTML5 required attribute in Javascript?
  • What is the worst programming language you ever worked with?
  • Specifying java version in maven - differences…
  • D3.js: Update barplot based on variable input
  • d3.js - draw arrow line from border to border
  • Identifying and solving…
  • How to add class active on specific li on user click…
  • "Thinking in AngularJS" if I have a jQuery background?
  • What are the new features in C++17?
  • What are the currently supported CSS selectors…
  • Sort table rows In Bootstrap
  • Examples of GoF Design Patterns in Java's core libraries
  • Reference — What does this symbol mean in PHP?
  • does Backbone.Models this.get() copy an entire array…
  • jqGrd hyperlink or showlink
  • Failed to mount component on new laravel 5.5 project
  • Ukkonen's suffix tree algorithm in plain English
  • Install vue 3.0 in laravel
  • Laravel Vue.js wont update file to server
  • AppCompat v7 r21 returning error in values.xml?
  • How to properly do JSON API GET requests and assign…
  • After a little scroll, the sticky navbar just is not…
  • What does "Fatal error: Unexpectedly found nil while…
  • Only one element is appended in the div
  • What does this symbol mean in JavaScript?
  • How to calculate Cohen's D across 50 points in R
  • npm install error in vue
  • Is it possible to apply CSS to half of a character?
  • Can't install via pip because of egg_info error
  • What is a NullReferenceException, and how do I fix it?
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • integrating disqus with emberjs only works on first…
  • .prop() vs .attr()
  • regex match any single character (one character only)
  • PHP parse/syntax errors; and how to solve them
  • jQuery Mobile: document ready vs. page events
  • Usage of __slots__?
  • Why does C++ code for testing the Collatz conjecture…
  • How can I manually compile a svelte component down…
  • SQL query return data from multiple tables
  • Laravel - npm run watch does not work on Lara 7,…
  • d3.js - Force simulation drag does not move with the mouse
  • How can we load color from a sequential scale into a…
  • Why call git branch --unset-upstream to fixup?
  • @selector() in Swift?
  • How do I remove single children in a tree?
  • Does "git fetch --tags" include "git fetch"?
  • Images have absolute path - How to use a…
  • jQuery: Adding two attributes via the .attr(); method
  • Jetty: HTTP ERROR: 503/ Service Unavailable
  • d3.js - dragmove circle with v6 not work as expected
  • Smart way to truncate long strings
  • Push git commits & tags simultaneously
  • Logging best practices
  • How to disable HTML links
  • Apply attribute-sets on existing elements
  • How to add css image backgrounds in Vue-js so…
  • What is your most productive shortcut with Vim?
  • Why is Ember throwing "Uncaught Error: Assertion…
  • Using underscore.js to copy backbone.js Model…
  • Getting started with Haskell
  • How does PHP 'foreach' actually work?
  • How can I find the product GUID of an installed MSI setup?
  • Start redis-server with config file
  • Implement javascript instance store by returning…
  • What is git tag, How to create tags & How to…
  • How to find Control in TemplateField of GridView?
  • How to instantiate route in a Polymer app located on…
  • Memcached vs. Redis?
  • How can I use/create dynamic template to compile…
  • How do you parse and process HTML/XML in PHP?
  • How to filter a RecyclerView with a SearchView
  • Ember data createRecord not working: "TypeError:…
  • How to generate a random string of a fixed length in Go?
  • Navbar not filling width of page when reduced to mobile view
  • The null object does not have a method []=
  • HTML5 Canvas Resize (Downscale) Image High Quality?
  • Defining custom attrs
  • Example using Hyperlink in WPF
  • The definitive guide to form-based website authentication
  • How to render web component in Polymer
  • vue 2.0 Failed to mount component: template or…
  • How to use Servlets and Ajax?
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Declaring a custom android UI element using XML
  • Downloading jQuery UI CSS from Google's CDN
  • Polymer - simple way to access child element…
  • data.table vs dplyr: can one do something well the…
  • Typeerror: n is undefined in underscore.min.js
  • Multiple items from DropDownList with protected sheet
  • Neither BindingResult nor plain target object for…
  • For-each over an array in JavaScript
  • How to resolve "Could not find schema information…
  • why preventdefault/stopPropagation not working in…
  • Laravel 5 Vue hot module replacement (HMR)
  • Use of Jquery on scroll event
  • What are the undocumented features and limitations…
  • Add Keypair to existing EC2 instance
  • How do I stop Aurelia from throwing JS Errors, when…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

C# DateTime to “YYYYMMDDHHMMSS” format

Next Post:

What’s the difference between using “let” and “var”?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error