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
.
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.
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.
We can remove the href by: Setting an empty href – ELEMENT. href = "" Or removing it entirely – ELEMENT.
$('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.
var href = $(this).attr('href');
$(this).attr('href', href + '&thisisadded=true')
Obviously do this in an context where this
is your link
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With