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
  • http://mydomain.com/path/to/page
  • https://mydomain.com/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.host === 'mydomain.com' || this.getAttribute('href').indexOf('/') === 0) {
        this.href = "/#" + this.pathname;
    }
});

It checks to see if the href.host matches the domain.com 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*='https://mydomain.com/path/to/page' ahref*='/path/to/page'  ahref*='http://mydomain.com/path/to/page'")

This should replace all the hrefs

$("ahref*='https://mydomain.com/path/to/page' ahref*='/path/to/page'  ahref*='http://mydomain.com/path/to/page'").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

$("a").each(
    function(index,element) {
        if(element.href.indexOf("https://mydomain.com/")==0) {
            $("a").attr("href",element.href.replace("https://mydomain.com/","/#/"));
        }
    }
}

,

pretty simple one

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

Leave a Comment