Home > Software design >  How to find all div which have style background-image?
How to find all div which have style background-image?

Time:01-01

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

CodePudding user response:

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));
});

CodePudding user response:

I got another solution

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