tags:

views:

332

answers:

3

I am trying to amend a link using jQuery. The links are dynamically generated and I have no control over the existing HREF as they are called from a 3rd party site.

Using jQuery, how can I change a link from this:

example.com/?one=1&two=1

to this:

example.com/?one=1&two=1&thisisadded=true

so essentially adding &thisisadded=true to the end of the link?

The links which need changing are within their own div with a class of my-link.

Many thanks for any help!

James

+6  A: 
$('a.my-link').each(function () {
    var href = $(this).attr('href');
    $(this).attr('href', href + '&thisisadded=true');
});

Replace selector with a jQuery selector that will match appropriate link on your site if mine is not good enought.

RaYell
James
A: 
var href = $(this).attr('href');
 $(this).attr('href', href + '&thisisadded=true')

Obviously do this in an context where this is your link

Teja Kantamneni
`$(this)` will work in callback once you match all links that needs to be changed. But if you just call your code like this it won't give you the results you'd expect.
RaYell
Yes, thats what I mentioned too, that you should be in that context, this can be used on any event on that element, isn't it?
Teja Kantamneni
+1  A: 

Just use your selector, and a callback function to attr. This will add the additional part to every matching link:

$('a.my_link').attr('href', function(i, a){ return a + "&thisadded=true" });

When supplying a callback to the attr method, the first parameter is the index and the second parameter is the original attribute value. Whatever is returned from the callback becomes the new value.

Note: This feature is available in jQuery 1.1 and later. Don't get this method confused with the new batch of methods that accept callbacks introduced in jQuery 1.4.

Doug Neiner
+1 Awesome tip regarding the attribute values!
Jonathan Sampson