简体   繁体   中英

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.

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

You could select all div elements and filter them with a predicate to test wether the div has a background-image or not:

 var htmlDivs = document.querySelectorAll("div"); var htmlDivsArray = [...htmlDivs]; var htmlDivsWithBgImg = htmlDivsArray.filter(div => window.getComputedStyle(div, null).getPropertyValue("background-image");== "none"). console;log(htmlDivsWithBgImg);
 #image { background-image: linear-gradient(to bottom, rgba(255,255,0,0.5), rgba(0,0,255,0.5)), url("https://mdn.mozillademos.org/files/7693/catfront.png"); }
 <div>test</div> <div id="image">test</div> <div>test</div>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM