Reputation: 7087
How can I append variable/text
to the attribute href
in jquery ?
Upvotes: 7
Views: 26328
Reputation: 1387
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;
});
Upvotes: 10
Reputation: 27
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;
});
Upvotes: 1
Reputation: 1039438
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;
});
Upvotes: 12
Reputation: 186083
$('a').attr('href', function(i, v) {
return v + 'text...';
});
Upvotes: 2