7

How can I append variable/text to the attribute href in jquery ?

Kara
  • 5,996
  • 16
  • 49
  • 56
Steffi
  • 6,587
  • 24
  • 74
  • 121

4 Answers4

12

You could use the .attr() function:

var foo = 'foo=bar';
$('a#foo').attr('href', function(index, attr) {
    return attr + '?' + foo;
});

or:

$('a#foo').attr('href', function() {
    return this.href + '?' + foo;
});
Darin Dimitrov
  • 994,864
  • 265
  • 3,241
  • 2,902
10

You need to check if there is already a query string before appending items to the url based on the other examples you'd do something like.

var foo = 'foo=bar';
$('a').attr('href', function(index, attr) {
    return attr + (attr.indexOf('?') >=0 ? '&' : '?') + foo;
});
JohnC
  • 1,367
  • 11
  • 33
2
$('a').attr('href', function(i, v) {
    return v + 'text...';
});
Šime Vidas
  • 173,790
  • 60
  • 275
  • 374
1

If you use it repeatedly try .attr() as:

HTML: <a id='foo' href='#'>I am your father,.. nooooo</a>

var myparams = 'myvar=myvalue';
var myurl = 'TypeThe_NetscapeURL';
$('a#foo').attr('href', function() {
    return myurl + '?' + myparams;
});
zoombaro
  • 27
  • 4
  • Couple of comments: 1.that would work but it's actually overriding the value NOT appending. To append, get the value first $("#foo").attr('href') and then append whatever you need to it. 2. in example above you don't need a function which returns url. simple myurl+'?'+myparams should do it. This is a case of taking a url and appending to it. Setting it to an href is just a byproduct. Check out http://stackoverflow.com/questions/179713/how-to-change-the-href-for-a-hyperlink-using-jquery for setting hrefs – Alexey Gerasimov Dec 06 '12 at 21:12