SystemicPlural
SystemicPlural

Reputation: 5789

How to select all local links in jQuery

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

and replace them with

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.

Upvotes: 2

Views: 3136

Answers (4)

user113716
user113716

Reputation: 322492

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.

Upvotes: 2

user372551
user372551

Reputation:

pretty simple one

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

Upvotes: 0

dvhh
dvhh

Reputation: 4750

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/","/#/"));
        }
    }
}

Upvotes: 1

John Hartsock
John Hartsock

Reputation: 86872

This should select all the anchor tags.

$("a[href*='https://mydomain.com/path/to/page'] a[href*='/path/to/page']  a[href*='http://mydomain.com/path/to/page']")

This should replace all the hrefs

$("a[href*='https://mydomain.com/path/to/page'] a[href*='/path/to/page']  a[href*='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));

})

Upvotes: 1

Related Questions