Sven Koluem
Sven Koluem

Reputation: 687

How to find all elements with a specified backgroundimage

i am searching for a way to select all objects, with a specified backgroundImage. I have already tried things like:

$.each($('*'), function(){
  if ($(this).css('backgroundImage')){
    console.info("backroundimage");
  }else {
    console.info("no backgroundimage");
  }
});

Some better ideas?

Upvotes: 3

Views: 2143

Answers (4)

Steve
Steve

Reputation: 3663

You pretty much achieved the crux of it there.

To expand upon what you have already:

$('*').each(function(){

    var bgImgStr = $(this).css('backgroundImage'),
        regEx = /\"|\'|\)/g,
        bgImgName = bgImgStr.split('/').pop().replace(regEx,'');

    if(bgImgName === 'whatever.jpg'){

        // do something

    }

});

Incedentally, the regEx part srtips everything but the filename (if one exists). The reason for this addition is because - depending on the browser - you may find yourself with something like:

url('../images/myImg.jpg')

Upvotes: 1

Grant Thomas
Grant Thomas

Reputation: 45083

You're sort of on the right track:

var url = $(this).css("background-image");
if (url == theExpectedImageUrl) {
  //found image
});

But as noted in comments, doing this for all elements perhaps isn't the way to go!

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382686

One way:

var elementsWithBG = $('.YourSelector').filter(function(){
    return this.style.backgroundImage != ''
});

Of course not all elements will have a background such as span, links, etc. Using * is expensive, you can separate needed elements with a comma instead of '.YourSelector' eg:

$('div, p, etc')

Upvotes: 3

jenson-button-event
jenson-button-event

Reputation: 18941

Filters?

$('*').filter(function() {
     return $(this).css('background-image') == 'image.png';
});

Upvotes: 4

Related Questions