Checking the background-image of an element

3

I would like to know how to check if any element has a certain background with pure Javascript (without jQuery).

With jQuery I can use this:

if( $('.icon').css('background-image') === 'url(http://i56.servimg.com/u/f56/12/05/75/97/e410.png)' ){
    //do something
}

But I'm having trouble doing pure Javascript. (remembering that there are several .icon elements on the page, I would like the code to have effect only if it has that specific background ...)

    
asked by anonymous 14.06.2014 / 17:00

1 answer

3

In javascript, for now, you have to use a for loop and getComputedStyle

var icons = document.querySelectorAll('.icon');
var imagem = 'url(http://i56.servimg.com/u/f56/12/05/75/97/e410.png)';
for (var i = 0; i < icons.length; i++) {
    var este = window.getComputedStyle(icons[i]).backgroundImage;
    if (este == imagem) {
        // fazer algo
        console.log('Tem imagem!');
    }
}

Example: link

This code above will run the if to each element. If you want to run only if all elements timer this image, then you have to create a flag. For example:

var todos = true;
var icons = document.querySelectorAll('.icon');
var imagem = 'url(http://i56.servimg.com/u/f56/12/05/75/97/e410.png)';
for (var i = 0; i < icons.length; i++) {
    var este = window.getComputedStyle(icons[i]).backgroundImage;
    if (este == imagem) flag = false;
}
if (todos){
    // aqui sim pode correr o seu código
}
    
14.06.2014 / 17:13