7

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

Kara
  • 6,115
  • 16
  • 50
  • 57
Steffi
  • 6,835
  • 25
  • 78
  • 123

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
  • 1,023,142
  • 271
  • 3,287
  • 2,928
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,377
  • 11
  • 33
2
$('a').attr('href', function(i, v) {
    return v + 'text...';
});
Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
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