Question

How to Change the href Attribute with jQuery

htmljavascriptjqueryhyperlink

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 href is 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.

Take Quiz

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>
$('.nav-link').attr('href', '/dashboard');

Now both links will point to /dashboard.

Example 3: Set the link after a button click

<a id="productLink" href="/product/1">View product</a>
<button id="changeLink">Load another product</button>
$('#changeLink').on('click', function () {
  $('#productLink').attr('href', '/product/2');
});

This updates the link only when the button is clicked.

Example 4: Read the current href

var currentHref = $('#myLink').attr('href');
console.log(currentHref);

With one argument, .attr('href') reads the attribute value instead of changing it.

Step by Step Execution

Consider this example:

<a id="helpLink" href="/help">Help</a>
$('#helpLink').attr('href', '/support');

Step by step:

  1. $('#helpLink')

    • jQuery searches the page for the element with id="helpLink".
    • It creates a jQuery object containing that link.
  2. .attr('href', '/support')

    • jQuery looks at the selected element.
    • It finds the href attribute.
    • It replaces the old value /help with /support.
  3. Result

    • The HTML effectively becomes:
<a id="helpLink" href="/support">Help</a>
  1. User action
    • When the user clicks the link, the browser now goes to /support instead of /help.

Here is a slightly larger example:

<a id="profileLink" href="/users/1">Profile</a>
<button id="switchUser">Switch User</button>
$('#switchUser').on('click', function () {
  $('#profileLink').attr('href', '/users/2');
});

Execution flow:

  1. The page loads.
  2. The link starts with href="/users/1".
  3. A click handler is attached to the button.
  4. When the button is clicked, the function runs.
  5. Inside the function, jQuery updates the link's href to /users/2.
  6. Future clicks on the link go to the new user profile.

Real World Use Cases

Changing href dynamically is useful in many real applications.

Common examples

  • Language switching: update links to /en/docs or /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.

Take Quiz

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

<a id="reportLink" data-report-id="88" href="#">Open report</a>
var reportId = $('#reportLink').data('report-id');
$('#reportLink').attr('href', '/reports/' + reportId);

Event-driven updates

$('#planSelect').on('change', function () {
  var plan = $(this).val();
  $('#checkoutLink').attr('href', '/checkout?plan=' + plan);
});

These patterns are common because they separate:

  • where data comes from
  • how the URL is built
  • when the DOM is updated

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:

  • myLink is treated as a tag selector, not an id.

Correct code:

$('#myLink').attr('href', '/new-page');

3. Running code before the element exists

Broken code:

$('#myLink').attr('href', '/new-page');

If this runs before the link is loaded into the page, nothing is updated.

Correct approach:

$(document).ready(function () {
  $('#myLink').attr('href', '/new-page');
});

4. Using the wrong attribute name

Broken code:

$('#myLink').attr('src', '/new-page');

Why it fails:

  • src is used for elements like images and scripts, not hyperlinks.

Correct code:

$('#myLink').attr('href', '/new-page');

5. Expecting only one element when the selector matches many

$('.menu-link').attr('href', '/home');

This updates all matched links, not just one.

To change one specific link, use a more precise selector.

6. Forgetting that .attr('href') reads and .attr('href', value) writes

var href = $('#myLink').attr('href');

This reads the value.

$('#myLink').attr('href', '/contact');

This writes the value.

Comparisons

jQuery .attr() vs plain JavaScript

ApproachExampleWhen to use
jQuery$('#myLink').attr('href', '/new')When your project already uses jQuery
Plain JavaScriptdocument.getElementById('myLink').setAttribute('href', '/new')When you do not need jQuery
Plain JavaScript propertydocument.getElementById('myLink').href = '/new'Simple direct DOM work

Reading vs writing with .attr()

UsageMeaning
.attr('href')Get the current href value
.attr('href', '/new')Set a new href value

.attr() vs .prop()

MethodBest forExample
.attr()HTML attributes$('#link').attr('href', '/home')
.prop()DOM properties like checked, disabled, selected$('#box').prop('checked', true)

For hyperlinks, .attr('href', value) is the usual jQuery approach.

Take Quiz

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 .attr() for HTML attributes
  • Use href for links
  • Use #id for ids and .class for classes
  • If using jQuery, make sure the element exists before updating it
  • One argument reads; two arguments write

Common pattern

$(document).ready(function () {
  $('#myLink').attr('href', '/new-page');
});

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 src instead of href

Should I use .attr() or .prop() for links?

For hyperlinks, use .attr() to work with the href attribute.

Can I change the href after a button click?

Yes. Attach an event handler and update the link inside it.

$('#btn').on('click', function () {
  $('#myLink').attr('href', '/new-target');
});
Take Quiz

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

  1. Create a hyperlink that starts with a default product URL.
  2. Add a dropdown with at least three product IDs.
  3. Update the link's href when the dropdown value changes.
  4. Keep the visible link text meaningful.
  5. Use jQuery for the DOM selection and update logic.
Take Quiz

Keep learning

Related questions

View more