Replace all href's within a div element by adding = infront for example. if the html is...
<div class="post-body">
<a href="">google</a>
<a href="">youtube</a>
<a href="">facebook</a>
</div>
replace each href by adding = infront so the oute of the html will be...
<div class="post-body">
<a href="://www.google">google</a>
<a href="://www.youtube">youtube</a>
<a href="://www.facebook">facebook</a>
</div>
Replace all href's within a div element by adding http://mysite.?url= infront for example. if the html is...
<div class="post-body">
<a href="http://www.google.">google</a>
<a href="http://www.youtube.">youtube</a>
<a href="http://www.facebook.">facebook</a>
</div>
replace each href by adding http://mysite.?url= infront so the oute of the html will be...
<div class="post-body">
<a href="http://mysite.?url=http://www.google.">google</a>
<a href="http://mysite.?url=http://www.youtube.">youtube</a>
<a href="http://mysite.?url=http://www.facebook.">facebook</a>
</div>
Share
Improve this question
asked Oct 25, 2011 at 16:48
Yusaf KhaliqYusaf Khaliq
3,39311 gold badges45 silver badges82 bronze badges
5 Answers
Reset to default 6Using jQuery.each
$('.post-body a').each(function () {
var $this = $(this),
href = $this.attr('href');
$this.attr('href', "http://mysite./?url=" + href);
})
Example
You can use directly the .attr()
method
$('.post-body a').attr('href', function(i, currentValue){
return 'http://mysite.?url=' + currentValue;
});
Demo at http://jsfiddle/gaby/94Bf4/
Use jQuery's $.each
method: http://jsfiddle/bFEzt/
$.each($('.post-body a'),function() {
$(this).attr('href',"http://domain./?url="+$(this).attr('href'));
});
simple
$.each("a",function(index, elem){
$(elem).attr('href','http://mysite.?url=' + $(elem).attr('href'));
});
You can do this in one line of code with replace
:
$('div.post-body').html(
$('div.post-body').html().replace(/href="/g,'href="http://mysite.?url=')
);