blackghost
blackghost

Reputation: 703

Check if an element has a background-image with pure JS?

What is the correct way to check if a particular element has a background-image associated with it, in pure Javascript?

Right now I have this:

var elementComputedStyle = window.getComputedStyle(element); 
var hasBGImage = elementComputedStyle.getPropertyValue('background-image') !== 'none'

Upvotes: 1

Views: 7429

Answers (3)

Adan Luna
Adan Luna

Reputation: 11

I used this code in last one project and works perfect

    // Check all background images exists
var imageURLs = $('.image-container ');
imageURLs.each(function(index, element){
    var imageURL = $(element).css('background-image').replace('url("', '').replace('")', '');
    var img = new Image();
    img.onerror = function() { $(element).css('background-image','url(/build/images/missing-image.svg)'); };
    img.src = imageURL;
});

Upvotes: 0

Flavio Giobergia
Flavio Giobergia

Reputation: 399

Make sure you declare the background image "inline", otherwise .style.backgroundImage won't work.

<script>
window.onload=function() {
    var bg = document.getElementById('el').style.backgroundImage.length!=0;
    alert(bg);
}
</script>
<div id='el' style="background-image: url('a.jpg');"></div>

If you can use inline CSS, that's the way. If, for some reason, you can't use that, let me know, I'll try to find out something else :)

Upvotes: 0

Curlystraw
Curlystraw

Reputation: 229

What you have works, but there are alternate ways of finding the property that you might find easier. I don't believe there is a single 'correct' way to do it, however.

Just javascript:

var hasBGImage = element.style.backgroundImage !== '';

Using jQuery:

var hasBGImage = $(element).css('background-image') !== 'none';

Upvotes: 4

Related Questions