Reputation: 23
so I have this html code with jquery imported
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<div class="col-xs-12 col-sm-7 col-md-12 no_padding" id="vdp_buttons">
<a href="/quote/1312678/cta_request.php" class="btn btn-success cta vdp-cta col-xs-12 col-md-5 col-lg-2">
Request Something
</a><br>
<a href="/test_drive/1312678/cta_request.php" class="btn btn-success cta vdp-cta col-xs-12 col-md-5 col-lg-2">
Test Something
</a><br>
<a href="/availability/1312678/cta_request.php" class="btn btn-success cta vdp-cta col-xs-12 col-md-5 col-lg-3">
Check Something
</a><br>
<a href="/appraisal/1312678/cta_request.php" class="btn btn-success cta vdp-cta col-xs-12 col-md-5 col-lg-3">
Trade Something
</a><br>
</div>
<script>
//Something goes here
</script>
I want to use jquery to change one of those links, but all the classes are the same. The only thing I can reference is the id "vdp_buttons". Is there a way using jquery or javascript to iterate through each link and change a specific href in this case, or is it not possible?
Upvotes: 2
Views: 56
Reputation: 302
Jquery to loop through all anchors:
$( document ).ready(function() {
$('a').each(function (i, v) {
alert(this.href);
});
});
Put this in your tag and you will see each href. Change via
this.href = "http://www.google.com"
Upvotes: 0
Reputation: 439
You can iterate through all your link tags and change the href when some condition holds as follows.
$("a").each(function() {
var href = $(this).attr('href');
if ( href == '/old/link') {
$(this).attr('href', 'this/is/new/link')
}
});
Upvotes: 1
Reputation: 4230
You need use the select using href
attribute, see below.
$("#vdp_buttons [href='/appraisal/1312678/cta_request.php']").attr("href","newlink")
DEMO :
$("#vdp_buttons [href='/appraisal/1312678/cta_request.php']").attr("href","newlink");
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-xs-12 col-sm-7 col-md-12 no_padding" id="vdp_buttons">
<a href="/quote/1312678/cta_request.php" class="btn btn-success cta vdp-cta col-xs-12 col-md-5 col-lg-2">
Request Something
</a><br>
<a href="/test_drive/1312678/cta_request.php" class="btn btn-success cta vdp-cta col-xs-12 col-md-5 col-lg-2">
Test Something
</a><br>
<a href="/availability/1312678/cta_request.php" class="btn btn-success cta vdp-cta col-xs-12 col-md-5 col-lg-3">
Check Something
</a><br>
<a href="/appraisal/1312678/cta_request.php" class="btn btn-success cta vdp-cta col-xs-12 col-md-5 col-lg-3">
Trade Something
</a><br>
</div>
Upvotes: 0