4

How can I select in jQuery all the divs that have background-image: url(somepath/somename.png) in their style?

Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746
frbry
  • 499
  • 2
  • 12
  • 25

3 Answers3

4

Try adding a custom selector:

$(document).ready(function() { 
    $.extend($.expr[':'], { 
        hasMyImage: function(el) { 
            return ($(el).css('background-image') == "Url('somepath/somename.png')");
        } 
    }); 
}); 

Then to select:

$("div:hasMyImage");
James Wiseman
  • 29,946
  • 17
  • 95
  • 158
  • A regexp would be required for a proper cross-browser match on `background-image`. Some browsers return the value with string identifiers (`'`), some don't. The case of `url()` could be different too. – Andy E Feb 12 '10 at 13:10
  • +1 this is great, didn't know you could define new selectors .. this will come in handy – Gabriele Petrioli Feb 12 '10 at 13:11
3

There isn't a jQuery selector, but this might work:

$('div').each( function() {
    if ( $(this).css('background-image') == 'url("image.png")' ) {
        // do something here
    }
});

However, a more efficient method would be to make sure you only have a single class that uses that background image, then simply select $('.bgClass')

DisgruntledGoat
  • 70,219
  • 68
  • 205
  • 290
  • The problem is i have no access to the code generating the element. It's a weather web part and background-image address changes all the time. The div has no class. These points lead me to this question. – frbry Feb 12 '10 at 13:10
1

Use the filter function:

var matches = $("div").filter(function() 
{      
    return ($(this).css("background-image") == "url('somepath/somename.png')");
});
Tim S. Van Haren
  • 8,861
  • 2
  • 30
  • 34