Search code examples
jqueryparentattr

jQuery modify image's parent a tag depending on image src


I have a page that loads an image at random. With jQuery, I'd like to check the image's src and, depending on what that src contains, modify the href of the image's parent a tag.

Here's what I've written so far, with no luck:

<div class="hero">
    <div class="inner">
        <a href="#"><img src="http://encompassomaha.com/wp-content/uploads/2013/05/copy-2.png" class="header-image" width="960" height="250" alt="" /></a>
    </div>
</div>



jQuery(document).ready(function($) {
    $('.hero .inner a img').each(function(i){
        var img = $(this),
        imgSrc = img.attr('src');

        if(imgSrc.contains('copy-2.png')){
            img.parent().attr('href', 'http://google.com');
        }
     }
}

Solution

  • Try with this:

    http://jsfiddle.net/RLQLh/5/

    and with http://jsfiddle.net/RLQLh/6/

    with your selector

    $('.hero .inner a img').each(function(i){
    

    both use

    if(imgSrc.indexOf('copy-2.pn') !== -1)
    

    instead of string Contains()