Search code examples
jqueryeachsrcattr

Using jQuery each to replace image source


I have the following issue. On load I want to use each to go through all the divs with the ".image" class, get the source of the image in that div and replace the source of the corresponding list item.

Example below: useThis1 will replace the source of item1, useThis2 will replace the source of item2, so on and so forth. Any help on this would be much appreciated.

<div class="image"><img src="useThis1"/></div>
<div class="image"><img src="useThis2"/></div>
<div class="image"><img src="useThis3"/></div>
<div class="image"><img src="useThis4"/></div>
<div class="image"><img src="useThis5"/></div>

<div id="contentA">
<ul>
<li><img id="item1" src="toReplaceThis"></li>
<li><img id="item2" src="toReplaceThis"></li>
<li><img id="item3" src="toReplaceThis"></li>
<li><img id="item4" src="toReplaceThis"></li>
<li><img id="item5" src="toReplaceThis"></li>
</ul>
</div>

Solution

  • var dvImages = $('.image img');  //array of usethis images
    var liImages = $('#contentA img'); //array of item images
    
    $.each(dvImages, function(index){
        if(index == liImages.length)
            return false;
        $(liImages[index]).attr('src', $(this).attr('src'));
    });
    

    Wrap the function in $(document).ready() if you want it to execute when the DOM is fully loaded.