How can I append variable/text
to the attribute href
in jquery ?
Asked
Active
Viewed 2.6k times
4 Answers
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
-
1This doesn't take into consideration what the existing url is – JohnC Jun 26 '14 at 13:09
-
3This will break urls which already have a querystring. Have a look at @JohnC's answer. – Tom Bowers Jun 26 '14 at 13:11
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
-
@Steffi The index of the element inside the jQuery object - irrelevant in this case. – Šime Vidas Mar 27 '11 at 20:30
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