Dancer
Dancer

Reputation: 17671

Jquery : Append querystring to all links

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?

Upvotes: 21

Views: 20512

Answers (2)

Paul Fleming
Paul Fleming

Reputation: 24526

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.

Upvotes: 49

Rabih
Rabih

Reputation: 318

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);

Upvotes: 4

Related Questions