user3308138
user3308138

Reputation: 11

selecting all the image sources in a class in jQuery

I'm trying to select all the image sources in a class in jQuery and assign a new src if they meet a certain criteria.

This is how I've started

$(document).ready(function() 
{ 
    $('.clear_compare_btn').click(function(event){
        if ($(".myclass").attr("img") == "static/img/compare_checked.png")  {} 
    });
});

I'm not sure if the above just checks the first image in elements that contain myclass? How would I check each one and replace the src if the src is "static/img/compare_checked.png" ?

Upvotes: 0

Views: 39

Answers (2)

Reger
Reger

Reputation: 474

Using each:

$('.clear_compare_btn').each( function() {
    if ($(this).attr("img") == "static/img/compare_checked.png") {
        //your code here
    }
});

Upvotes: 0

Kirk
Kirk

Reputation: 513

Should it be

$('img.myclass').each(function( index ) {
  if ($(this).attr('src') == 'static/img/compare_checked.png') {}
});

For how each works: https://api.jquery.com/each/

Upvotes: 1

Related Questions