How can I append variable/text to the attribute href in jquery ?
4 Answers
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;
});
2 Comments
JohnC
This doesn't take into consideration what the existing url is
Tom Bowers
This will break urls which already have a querystring. Have a look at @JohnC's answer.
$('a').attr('href', function(i, v) {
return v + 'text...';
});
1 Comment
Šime Vidas
@Steffi The index of the element inside the jQuery object - irrelevant in this case.
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;
});
1 Comment
Alexey Gerasimov
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 stackoverflow.com/questions/179713/… for setting hrefs