Search code examples
javascriptjqueryreplacehref

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?


Solution

  • 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.