21

I would like to append a query string onto all dynamic links within a page - to fix a bug in a old release - is this possible?

Any ideas?

Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
Dancer
  • 17,035
  • 38
  • 129
  • 206

2 Answers2

49

Something like this?

var querystring = 'myquerystringtoadd';

$('a').each(function() {
    var href = $(this).attr('href');

    if (href) {
        href += (href.match(/\?/) ? '&' : '?') + querystring;
        $(this).attr('href', href);
    }
});

Working example.

Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
  • Better than @woz answer, because of the checking for existing querystring and either appending with & or prefixing with ? – jaygooby Sep 21 '12 at 16:35
  • 5
    @jaygooby. Yes. An additional check should also be made for url anchors ("#"). – Paul Fleming Sep 23 '12 at 12:47
  • @flem -1: this does not work. I think it should be `href.match(/\?/)`. – montrealist Mar 31 '13 at 06:46
  • @dalbaeb Nice spot. The `?` wasn't escaped. I've corrected the post and added a working fiddle. Thanks! If you're happy now, please remove the downvote :) – Paul Fleming Apr 01 '13 at 11:03
  • 1
    The only issue I came across with this is when an `a` tag didn't have an href property, so I just added `if(href) { href+= ...` into the mix to stop it from breaking on links like this. – Novocaine May 31 '13 at 10:48
  • @Novocaine88 Thanks for the comment. I've updated the code to reflect your suggestion. – Paul Fleming Sep 11 '13 at 14:08
4

This solution with native javascript :

var querystring = 'yourQueryStringHere=;-)';

document.addEventListener('click', function (e) {

    var x = e.originalTarget;
    if (x.nodeName === 'A') {

        var href = x.getAttribute('href');

        if(href) {
            href += (/\?/.test(href) ? '&' : '?') + querystring;
            x.setAttribute('href', href);
        }
    }

}, false);
Rabih
  • 298
  • 1
  • 6
  • 18