List of All Background Images in DOM

前端 未结 7 1110
旧巷少年郎
旧巷少年郎 2020-12-29 12:00

What\'s the best way to find all of the background images on a given page using javascript?

The ideal end result would be an array of all of the url\'s.

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-29 12:37

    Here's a way to check what background urls there are in the styles on the page (look Ma, no jQuery):

    window.npup = (function (doc) {
      var sheets = doc.styleSheets;
      var hash = {}, sheet, rules, rule, url, match;
      // loop the stylesheets
      for (var sheetIdx=0, sheetsLen=sheets.length; sheetIdx

    With this on the page you can get an array of urls with npup.getBackgroundUrls(); I did some (superfluos?) commenting in the code that explains how it goes about. It doesn't grab inlined styles, but I think that was no problem for you? Styles in external sheets and in