views:

47

answers:

3

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

Thanks.

+2  A: 

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
+1 for the suggestion about using a class.
Davide Gualano
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
+2  A: 

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
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
+1 this is great, didn't know you could define new selectors .. this will come in handy
Gaby
Agreed with Gaby.
frbry
+1  A: 

Use the filter function:

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