How to find all div which have style background-image?

Viewed 164

Is there any jquery or JS to file all div that have background image. I need to lazy load on these div.

3 Answers

There is a good post that shows you how to find all images (images, background-images, images in iframes): https://blog.crimx.com/2017/03/09/get-all-images-in-dom-including-background-en/
So, if you are trying to find all divs that have a background-image that's an image from an URL (not a gradient), this code would do it for you:

let divs = document.querySelectorAll("div");

let urlRegex = /url\(\s*?['"]?\s*?(\S+?)\s*?["']?\s*?\)/;

var divsWithBackgroundImage = Array.from(divs).filter((div) => {
    let backgroundImage = getComputedStyle(div).getPropertyValue("background-image");
  
    return (backgroundImage.match(urlRegex));
});

I got another solution

$('div').filter(function(){
    if(this.style.backgroundImage){
        console.log(this.style.backgroundImage);
    }
});

Another solution

$('div').each(function() {
    if($(this).css('background-image') != 'none'){
        console.log($(this).css('background-image').split(/"/)[1]);
    }
});
Related