How to change the target of any local link when clicked, using javascript / jquery? – Education Career Blog

I need to change the href of any local link when it is clicked on.
I’ve worked out how to select the correct links and create the new url, but not sure how to change the location. I need to be certain that any other click events have also run, so I can’t just change the location immediately.

var my_host = '';
$(document).click(function(e) {
    if( == my_host)
        alert( + "//" + + "/#" + +;

This is related to my earlier question.


You can bind the event on your local links like this and use the attr method to change the href:

  // your code before changing href
  $(this).attr('href', 'new url here');

Replace with your own domain so that the above code only targets your local links.


This is completely untested, but should get you where you’re going:

var site = "";

// Match anchor tags with an href value that starts with your
// site URL, or that start with / which are relative URLs (also
// your site).
$('ahref^="' + site + '" ahref^="/"').click(function(){
    var url = $(this).attr('href');
    if (url.indexOf(site) != -1) {
        url = site + "/#" + url.replace(site, ""); // Quick dirty way to get the path component of the URL
    } else {
        url = "/#" + url;
    $(this).attr("href", url);

Note that I read your other question, and I personally don’t understand why you would do this on a click event, instead of just replacing all the href values as soon as the page is loaded.


Credit to Sarfraz: here is the answer without the bug.

var my_host = "";
$('ahref^="/", ahref^="http://' + my_host + '", ahref^="https://' + my_host + '"').click(function(e){
    $(this).attr('href', + "//" + + "/#" + +;

Leave a Comment