Reputation: 1
I'm try to change all html anchor href link using jQuery but it's not work properly. When I click the button it's select the first link and replace everywhere.
var link = $('#content a[href]');
$("button").click(function() {
var lin = $("#content a").attr('href');
var rep = "http://example.com/?redirect=";
$("#content a[href]").attr("href", rep + "" + $("#content a").attr('href'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
<a href="http://google.com">Google</a>
<a href="http://fb.com">Facebook</a>
</div>
<button>Click</button>
<div class="p"></div>
Upvotes: 0
Views: 2469
Reputation: 16855
You are using $("#content a").attr('href')
to replace the href
...It will find the first match and replace to all
You have to use each()
to find all the links and then use $(this).attr('href')
to differentiate
Stack Snippet
$(document).ready(function() {
$("button").click(function() {
var rep = "http://example.com/?redirect=";
$("#content a[href]").each(function() {
$(this).attr("href", rep + "" + $(this).attr('href'));
})
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
<a href="http://google.com">Google</a>
<a href="http://fb.com">Facebook</a>
</div>
<button>Click</button>
<div class="p"></div>
Upvotes: 3