Question

I'm trying to select an element based on its background-image. That image is defined inline.

<div class="el" style="background-image:url(http://cl.ly/010.jpg);"></div>

I've already tried using the common solutions but with no result.

$('.el').each(function() {
    if ( $(this).css('background-image') === 'http://cl.ly/010.jpg' ) console.log('found it');
});

or

var current = $('.el').css('background-image', 'url(http://cl.ly/010.jpg)');

jQuery doesn't find the image. I've even tried to iterate trough every single element and I've double checked the url. Everything seems fine so far.

Any Ideas what could be wrong here ?

Thank you

Was it helpful?

Solution

Try

if ($(this).css('background-image') === 'url(http://cl.ly/010.jpg)') console.log('found it');

with url() in search the string.

OTHER TIPS

Check this fiddle for a working example.

You were missing quotes on the .el selector on this line:

var current = $('.el').css('background-image') === "url(http://cl.ly/010.jpg)"

Edit: You fixed the quotes, but in the second code block, you had only the URL, not the actual CSS value "url(...)". It should look like:

$('.el').each(function() {
    if ( $(this).css('background-image') === 'url(http://cl.ly/010.jpg)' ) console.log('found    it');
});

You need to include the url when you are checking. Check out this fiddle: http://jsfiddle.net/vL4pG/

$('.el').each(function(){
   var $this = $(this);

    if ($this.css('background-image') === 'url(http://cl.ly/010.jpg)'){
         alert('found it');   
    }
});

Use this:

var current = $('.el').css('background-image') === "url(http://cl.ly/010.jpg)"


Here's a fiddle (used a different address for the image) Fiddle


For your code, the first is incorrect because you need the url() wrapper, like this:

$('.el').each(function() {
if ( $(this).css('background-image') === 'url(http://cl.ly/010.jpg)' ) console.log('found    it');
});


Your second is incorrect because you are missing the quotes on the class, should be this:

var current = $('.el').css('background-image', 'url(http://cl.ly/010.jpg)');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top