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.get
Solution 1:
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';
Solution 2:
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><divid='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 :)
Solution 3:
I used this code in last one project and works perfect
// Check all background images existsvar imageURLs = $('.image-container ');
imageURLs.each(function(index, element){
var imageURL = $(element).css('background-image').replace('url("', '').replace('")', '');
var img = newImage();
img.onerror = function() { $(element).css('background-image','url(/build/images/missing-image.svg)'); };
img.src = imageURL;
});
Post a Comment for "Check If An Element Has A Background-image With Pure Js?"