33

Morning all,

I have a list of images like so:

<ul id="preload" style="display:none;">
<li><img src="afx4000z-navy-icon-1_thumb.jpg"/></li>
<li><img src="afx4000z-green-icon-1_thumb.jpg"/></li>
</ul>

Using jQuery how find all image src's within ul#preload that contain a specific string eg."green"

something like...

var new_src = jQuery('#preload img').attr('src')*** that contains green ***;
Charles Web Dev
  • 429
  • 2
  • 7
  • 12

2 Answers2

66

You need to use the *= selector:

jQuery('#preload img[src*="green"]')

If you want it to be case insensitive, it will be a bit more difficult:

var keyword = "green";
$("#preload img").filter(function(keyword) {
    return $(this).attr("src").toLowerCase().indexOf(keyword.toLowerCase()) != -1;
});
Gabi Purcaru
  • 30,940
  • 9
  • 79
  • 95
  • Your second example would throw an error, numbers have no method `.toLowerCase()`. – Nick Craver Dec 21 '10 at 11:26
  • 2
    How can I use this logic to find all the images that dont have green in them? – dubbs Jun 19 '14 at 09:29
  • 1
    I believe `function(keyword)` there is misleading and semantically wrong. one option to fix it is simply changing it to `function()`. am I right, though? :P – cregox Sep 30 '16 at 20:00
10

You can use an attribute-contains selector ([attr*=value]), like this:

jQuery('#preload img[src*=green]')
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155