user9371102
user9371102

Reputation: 1276

how to append string to <a href=" with jQuery or Javascript?

I've the elements as follows,

<div id="pager">
<a href="/somepath/1">First</a>
<a href="/somepath/1">Previous</a>
<a class="" href="/somepath/1">1</a>
<a class="Current" href="/somepath/2">2</a>
<a class="" href="/somepath/3">3</a>
<a href="/somepath/3">Next</a>
<a href="/somepath/20">Last</a>
</div>

and I want it to be changed as follows within browser.

<div id="pager">
<a href="/somepath/1?a=text">First</a>
<a href="/somepath/1?a=text">Previous</a>
<a class="" href="/somepath/1?a=text">1</a>
<a class="Current" href="/somepath/2?a=text">2</a>
<a class="" href="/somepath/3?a=text">3</a>
<a href="/somepath/3?a=text">Next</a>
<a href="/somepath/20?a=text">Last</a>
</div>

So that I can use the "a" data values to next page. Can any one give me the code, which does the appends inside

div id="pager" -> <a> -> href="

and i wants to remove the added text with another onChange event.

Thanks in advance

Upvotes: 17

Views: 52242

Answers (7)

Blazemonger
Blazemonger

Reputation: 93003

.attr(), like many jQuery functions, can take a function argument that modifies the existing value:

$('#pager a').attr('href',function(i,str) {
   return str + '?a=text';
});

Upvotes: 15

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33880

Since jquery is tagged :

$('#pager a').each(function(){
     this.href += '?a=text';
})

Vanilla JS would look like this :

var a = document.getElementById('pager').getElementsByTagName('a'),
    length = a.length;

for(var i=0; i< length; i++){
    a[i].href += '?a=text';
}

Upvotes: 34

vikrant singh
vikrant singh

Reputation: 2111

$("#pager").find("a").each(function(){
var $this=$(this);
$this.attr("href",$this.attr("href")+"?a=text");
})

Upvotes: 3

Lucas Willems
Lucas Willems

Reputation: 7073

Try this code :

$('#pager a').each(function(){
    this.href += '?a=text'
})

Upvotes: 2

Aamir Shah
Aamir Shah

Reputation: 4493

Simply use the attr property. Example :-

$("a").attr("href", "http://www.google.com/")

This will do the job.

Upvotes: 5

Barış Uşaklı
Barış Uşaklı

Reputation: 13532

$('#pager a').each(function() {
   $(this).attr('href', $(this).attr('href') + '?a=text');
});

Upvotes: 6

Khawer Zeshan
Khawer Zeshan

Reputation: 9646

you can use attr method

$('a').attr('href', '/somepath/1?a=text');

And if you want to change the href of a specific <a> give that '' a unique id and than change its href as follows

$('#link').attr('href', '/somepath/1?a=text');

Upvotes: 2

Related Questions