James
James

Reputation: 61

jQuery: Adding text to an existing dynamic HREF

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.

Upvotes: 6

Views: 12893

Answers (3)

Doug Neiner
Doug Neiner

Reputation: 66191

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.

Upvotes: 1

Teja Kantamneni
Teja Kantamneni

Reputation: 17472

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

Obviously do this in an context where this is your link

Upvotes: 2

RaYell
RaYell

Reputation: 70404

$('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.

Upvotes: 12

Related Questions