7

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

4 Answers 4

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;
});
Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't take into consideration what the existing url is
This will break urls which already have a querystring. Have a look at @JohnC's answer.
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;
});

Comments

2
$('a').attr('href', function(i, v) {
    return v + 'text...';
});

1 Comment

@Steffi The index of the element inside the jQuery object - irrelevant in this case.
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;
});

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.