How to select all local links in jQuery – Education Career Blog

I need to select all local links, regardless of if the start with

  • /path/to/page

and replace them with

  • /#/path/to/page

Thanks for your help.

Edit: As pointed out by dvhh in a comment, a better solution would be to target clicks. So sorry, I won’t be testing solutions to mark a correct answer. Thanks for your help

Edit 2: Posted a new question about doing this via a click.


You should be able to do something like this:

$('a').each(function() {
    if ( === '' || this.getAttribute('href').indexOf('/') === 0) {
        this.href = "/#" + this.pathname;

It checks to see if the matches the or if the first character of href is /, and if so it sets the href to /# plus the current pathname part of the href.

I’m using the native getAttribute() because I think it is safest in terms of getting the actual original attribute that was set. Perhaps it wouldn’t make a difference.


This should select all the anchor tags.

$("ahref*='' ahref*='/path/to/page'  ahref*=''")

This should replace all the hrefs

$("ahref*='' ahref*='/path/to/page'  ahref*=''").each(function () {
  var $this = $(this);
  var currentHref = $this.attr('href');
  $this.attr("href","#/" + currentHref.substring(currentHref.indexOF("/path/to/page"), currentHref.length - 1));



what you requested for

    function(index,element) {
        if(element.href.indexOf("")==0) {


pretty simple one

$(function () {
    $('a').each(function () {
        $(this).attr('href', '/#' + pathname);

Leave a Comment