Question
How can you change the href attribute, which controls the destination of a hyperlink, by using jQuery?
Short Answer
By the end of this page, you will understand how jQuery changes HTML attributes, especially the href attribute on <a> elements. You will learn the basic syntax, see practical examples, understand how the code runs step by step, and avoid common mistakes when updating links dynamically.
Concept
In jQuery, you can read or change HTML element attributes by using the .attr() method. A hyperlink uses the href attribute to store the URL or destination it should open when clicked.
For example, this HTML link:
<a id="docsLink" href="/old-page">Documentation</a>
has an href attribute with the value /old-page.
To change that value with jQuery, you use:
$('#docsLink').attr('href', '/new-page');
This matters because many web pages update links dynamically based on:
- user actions
- selected options
- API responses
- environment settings
- tracking parameters
The key idea is simple:
- select the element with jQuery
- call
.attr() - provide the attribute name and the new value
When you pass two arguments to .attr(name, value), jQuery sets that attribute on every matched element.
Mental Model
Think of an HTML element like an object with labeled properties.
A link is like a door sign:
- the visible text is the label on the sign
- the
hrefis the destination written underneath
jQuery lets you walk up to the sign and rewrite the destination.
So if a link currently says:
- text:
Open Profile - destination:
/user/old
then .attr('href', '/user/new') changes where that door leads without needing to rewrite the whole element.
Syntax and Examples
The basic jQuery syntax is:
$(selector).attr('href', 'new-url');
Example 1: Change one link
<a id="myLink" href="https://example.com/old">Visit site</a>
$('#myLink').attr('href', 'https://example.com/new');
After this runs, the link will point to https://example.com/new.
Example 2: Change all links with a class
<a class="nav-link" href="/home">Home</a>
<a class="nav-link" href="/about">About</a>
Step by Step Execution
Consider this example:
<a id="helpLink" href="/help">Help</a>
$('#helpLink').attr('href', '/support');
Step by step:
-
$('#helpLink')- jQuery searches the page for the element with
id="helpLink". - It creates a jQuery object containing that link.
- jQuery searches the page for the element with
-
.attr('href', '/support')- jQuery looks at the selected element.
- It finds the
hrefattribute. - It replaces the old value
/helpwith/support.
-
Result
- The HTML effectively becomes:
<a = =>Help
Real World Use Cases
Changing href dynamically is useful in many real applications.
Common examples
- Language switching: update links to
/en/docsor/fr/docs - User-specific pages: point a profile link to the current user's page
- Search filters: build a link based on selected category or sort order
- Tracking links: append campaign parameters such as
?source=email - Admin dashboards: change action links depending on selected records
- Single-page interfaces: update links after loading data from the server
Example: Add a tracking parameter
$('#promoLink').attr('href', 'https://example.com/pricing?utm_source=newsletter');
Example: Build a user link from a value
var userId = 42;
$('#accountLink').attr('href', '/account/' + userId);
These are small changes, but they are common in interactive pages and dashboards.
Real Codebase Usage
In real projects, developers rarely hard-code every link update manually in many places. Instead, they use small patterns that keep the code safe and maintainable.
Common patterns
Guard clauses
Check that the element exists before updating it.
var $link = $('#settingsLink');
if ($link.length) {
$link.attr('href', '/settings/profile');
}
Build URLs from data
function buildProductUrl(productId) {
return '/products/' + productId;
}
$('#productLink').attr('href', buildProductUrl(15));
Update links after fetching data
var user = { id: 7, username: 'maya' };
$('#userLink').attr('href', '/users/' + user.id);
Use data attributes as inputs
Common Mistakes
Beginners often understand the idea but make small syntax or timing mistakes.
1. Forgetting to use .attr()
Broken code:
$('#myLink').href = '/new-page';
Why it fails:
$('#myLink')returns a jQuery object, not a plain DOM element.- You should use jQuery methods on it.
Correct code:
$('#myLink').attr('href', '/new-page');
2. Missing the # for an id selector
Broken code:
$('myLink').attr('href', '/new-page');
Why it fails:
myLinkis treated as a tag selector, not an id.
Correct code:
$('#myLink').(, );
Comparisons
jQuery .attr() vs plain JavaScript
| Approach | Example | When to use |
|---|---|---|
| jQuery | $('#myLink').attr('href', '/new') | When your project already uses jQuery |
| Plain JavaScript | document.getElementById('myLink').setAttribute('href', '/new') | When you do not need jQuery |
| Plain JavaScript property | document.getElementById('myLink').href = '/new' | Simple direct DOM work |
Reading vs writing with .attr()
| Usage | Meaning |
|---|---|
.attr('href') | Get the current value |
Cheat Sheet
Quick syntax
$(selector).attr('href', 'new-url');
Read current href
var url = $('#myLink').attr('href');
Set new href
$('#myLink').attr('href', '/contact');
Change multiple links
$('.nav-link').attr('href', '/dashboard');
Update after an event
$('#button').on('click', function () {
$('#myLink').attr('href', '/updated');
});
Rules to remember
- Use for HTML attributes
FAQ
How do you change a link URL in jQuery?
Use .attr('href', 'new-url') on the selected link element.
$('#myLink').attr('href', '/new-page');
How do I get the current href value with jQuery?
Use .attr('href') with one argument.
var href = $('#myLink').attr('href');
Can jQuery change multiple links at once?
Yes. If your selector matches multiple elements, jQuery updates all of them.
$('.nav-link').attr('href', '/home');
Why is my href not changing?
Common reasons include:
- wrong selector
- code runs before the element exists
- jQuery is not loaded
- you used
srcinstead ofhref
Should I use .attr() or for links?
Mini Project
Description
Build a small product link updater. The page starts with a link to one product and a dropdown of product IDs. When the user chooses a different product, the link should update automatically to point to the selected product page. This demonstrates selecting elements, handling events, reading values, and changing the href attribute with jQuery.
Goal
Create a page where selecting a product ID dynamically updates a hyperlink destination using jQuery.
Requirements
- Create a hyperlink that starts with a default product URL.
- Add a dropdown with at least three product IDs.
- Update the link's
hrefwhen the dropdown value changes. - Keep the visible link text meaningful.
- Use jQuery for the DOM selection and update logic.
Keep learning
Related questions
Can You Style Half a Character in CSS? Text Effects with CSS and JavaScript
Learn how to style half of a character using CSS and JavaScript, including overlay techniques for dynamic text effects.
Check If a Checkbox Is Checked with jQuery
Learn how to check whether a checkbox is checked in jQuery using the correct selector, with examples, mistakes, and practical patterns.
Convert HTML and CSS to PDF in PHP: Options, Limits, and Practical Approaches
Learn how HTML-to-PDF conversion works in PHP, why CSS support varies, and how to choose a practical approach for Linux web servers.