Sandeep Sherpur
Sandeep Sherpur

Reputation: 2802

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

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

Upvotes: 3

Views: 973

Answers (3)

Keivan Soleimani
Keivan Soleimani

Reputation: 510

Another solution

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

Upvotes: 0

Sandeep Sherpur
Sandeep Sherpur

Reputation: 2802

I got another solution

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

Upvotes: 0

Apollo79
Apollo79

Reputation: 704

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

Upvotes: 3

Related Questions