0

I'm looking to append a query string to the end of a link destination URL upon clicking the link, using jQuery or vanilla JS.

For example say I have this link: <a class="my-link-class" href="/my-url/">click me!</a>

I'd like to do something like:

$(".my-link-class").click(function() {
    ($this).attr('href').append('?my-string');  
});

But this doesn't work, I'm not sure why. I also can't simply add the string directly in my html, as the link destination is dynamic and changes depending on your current url.

Sam Assoum
  • 389
  • 1
  • 4
  • 18
  • Does this answer your question? [How to update (append to) an href in jquery?](https://stackoverflow.com/questions/2805742/how-to-update-append-to-an-href-in-jquery) – The Codesee Mar 26 '20 at 18:04
  • It also causes this "undefined" problem, same as Anurag Srivastava's solution. So my link becomes "/my-url/undefined/?string" – Sam Assoum Mar 26 '20 at 18:33
  • Ah i was missing a "." in front of my class in the var, this works! Thanks! – Sam Assoum Mar 26 '20 at 18:35

1 Answers1

0

You can use .attr( attributeName, function ) here like:

$(".my-link-class").click(function(evt) {
    evt.preventDefault()
    $(this).attr('href', (_, v) => `${v}?my-string`);
});

DEMO:

$(".my-link-class").click(function(evt) {
  evt.preventDefault()
  console.log( 'Before: ', $(this).attr('href') )
  
  $(this).attr('href', (_, v) => `${v}?my-string`);  
  
  console.log( 'After: ', $(this).attr('href') )
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="my-link-class" href="/my-url/">Click me!</a>
palaѕн
  • 64,836
  • 15
  • 100
  • 121
  • When I try this code, the link no longer functions, if I click on it nothing happens but I see it adds the query string to the destination, if I click it again it adds a second installment of the string but the link doesn't actually take you anywhere. – Sam Assoum Mar 26 '20 at 18:23