user1729506
user1729506

Reputation: 975

How can jQuery be used to make all relative paths absolute?

Using jQuery, I am trying to find any <a href="/folder/whatever.file">link</a> instances on a page and put http://www.domain.com before /folder.

What would be the easiest, safest way to do this?

Upvotes: 0

Views: 925

Answers (2)

Kevin B
Kevin B

Reputation: 95030

Update the href of the anchor tag when it is clicked.

$(document).on("click","a:not([href^=http])",function(){
    this.href = "http://domain.com" + this.href;
})

or better yet

$(document).on("click","a[href^=/specificfolder/]",function(){
    this.href = "http://domain.com" + this.href;
});

It would probably be better to make this change on your server using htaccess or similar url rewriting solutions.

Upvotes: 8

Adil Shaikh
Adil Shaikh

Reputation: 44740

$('a').each(function(){
  var href = $(this).prop('href')
  $(this).prop('href',"http://domain.com"+href);
});

Upvotes: 0

Related Questions