Search code examples
javascriptjqueryanchoranchor-scroll

Remove part of the link in a href before #anchor?


I have a link on my page as so:

<li class="jump"><a href="http://example.com/#about">About Me</a></li>

I'd like to use jQuery to remove the 'http://example.com/' part of any URL within a .jump class. Can you point me in the correct direction, with the simplest code possible? I want the code to remove anything before the hash, without specifying the URL (e.g. remove http://example.com/) in the jQuery code if possible.

thank you!


Solution

  • You can use:

    1) .each() to iterate over the all anchor

    2) split current href on occurence of # and use second array element

    3) concatenate the new href with # in front and set the new href

    $('.jump a').each(function(){
      $(this).attr('href','#'+$(this).attr('href').split('#')[1]);
    });