0

I've got a page full of links. I'm trying to add a querystring on the end of every one, so that:

http://www.example.com?x=1&y=2 becomes http://www.example.com?x=1&y=2&z=3

I want to parse every link and add this. I can't seem to find an elegant way of doing it using jQuery- any help would be much appreciated.

0

5 Answers 5

2

Something like this should work

$('a').each(function() {
  $(this).prop('href',$(this).prop('href') + '&z=3');
})

loop each a element and add z=3 to the end of the href property

Sign up to request clarification or add additional context in comments.

Comments

1

you could do:

$("a").attr('href', function(c, b) {
     return b + "&z=3";
});

Comments

1
$('a[href^="http://www.example.com"]').prop('href', function(i, href){
   return href + '&z=3';
})

Comments

0

This should do the trick.

$('a').each(function(){
  this = $this;
  curr_url = this.attr('href');
  this.attr('href', 'curr_url' + '&z=3');
});

Comments

0

You'll need to check this.attr('href').indexOf('?') > -1 before just adding a key/value pair. If there's no '?' you'll need to add that too.

You're probably best off using the native href API in javascript to parse the URL then add the bits you require to the part of the URL you require modified.

http://james.padolsey.com/javascript/parsing-urls-with-the-dom/

You should probably also consider doing this using an "on" event trigger (jQuery latest). Augmenting the DOM is slow when done to a lot of elements, and will delay page display if added in the onLoad hook.

$('body').on('click','a',function(e){
    // Prevent it jumping straight out
    e.preventDefault;
    // Define vars
    var href = this.href,
        qstr = 'a=b&bar=foo';
    // check for structure of url and add query string
    this.href += ((href.indexOf('?') > -1) ? '&': '?') + qstr;
    // jump
    return true;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.