Search code examples
jqueryhyperlinkhrefstaging

Prepend Subfolder to All Links with jQuery


I am currently working on a site in a staging environment located at www.example.com/staging. All of the links for the site have been set relatively (ex: /about/). I am trying to write some simple jQuery to add "/staging" to every link on the pages, so I don't have to change all the links for the week or so it is in the staging environment. I know the HTML tag is an option, but because the links are being added dynamically with ExpressionEngine that doesn't seem to work. I think the jQuery should be fairly simple. Here is what I have, but something isn't quite right:

$(function() {
  var href = $('a').attr('href');
  $(href).prepend('/staging');
});

Thanks in advance for the help.


Solution

  • Try this:

    $(function() {
      $('a').each(function() {
        var href = $(this).attr('href');
        $(this).attr('href', '/staging' + href);
      });
    });