Check the background-image of an element

Asked

Viewed 75 times

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 difficulty to do it via pure Javascript. (remembering that there are several elements .icon on the page, I would like the code to have effect only if it has that specific background...)

1 answer

3


In javascript, for now, you have to use a cycle for and the 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: http://jsfiddle.net/7zrk3/

This code above will run if to each elementto. If you want to run only if all the elements timerem that 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
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.