How can I append variable/text
to the attribute href
in jquery ?
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;
});
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;
});
$('a').attr('href', function(i, v) {
return v + 'text...';
});
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With