Search code examples
javascriptjqueryhtmliterationhref

changing an href using javascript in a class containing matching classes


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?


Solution

  • 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')
        }
    });