Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Adding text to an existing dynamic HREF

Tags:

jquery

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.

like image 871
James Avatar asked Feb 12 '10 14:02

James


People also ask

How to add value to href with jQuery?

Answer: Use the jQuery . attr() Method You can use the jQuery . attr() method to dynamically set or change the value of href attribute of a link or anchor tag. This method can also be used to get the value of any attribute.

How to insert before in jQuery?

jQuery insertBefore() Method The insertBefore() method inserts HTML elements before the selected elements. Tip: To insert HTML elements after the selected elements, use the insertAfter() method.

How do you remove a href?

We can remove the href by: Setting an empty href – ELEMENT. href = "" Or removing it entirely – ELEMENT.


3 Answers

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

like image 193
RaYell Avatar answered Oct 24 '22 19:10

RaYell


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

Obviously do this in an context where this is your link

like image 28
Teja Kantamneni Avatar answered Oct 24 '22 18:10

Teja Kantamneni


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.

like image 39
Doug Neiner Avatar answered Oct 24 '22 18:10

Doug Neiner