Selecting all the divs with png background-image

2019-06-27 04:41发布

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

3条回答
甜甜的少女心
2楼-- · 2019-06-27 04:51

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')

查看更多
倾城 Initia
3楼-- · 2019-06-27 04:53

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");
查看更多
祖国的老花朵
4楼-- · 2019-06-27 05:06

Use the filter function:

var matches = $("div").filter(function() 
{      
    return ($(this).css("background-image") == "url('somepath/somename.png')");
});
查看更多
登录 后发表回答