List of All Background Images in DOM

前端 未结 7 1082
旧巷少年郎
旧巷少年郎 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条回答
  •  伪装坚强ぢ
    2020-12-29 12:42

    Without using jQuery, you can do:

    var elementNames = ["div", "body", "td"] // Put all the tags you want bg images for here
    var allBackgroundURLs = new Array();
    elementNames.forEach( function(tagName) {
         var tags = document.getElementsByTagName(tagName);
         var numTags = tags.length;
         for (var i = 0; i < numTags; i++) {
             tag = tags[i];
             if (tag.style.background.match("url")) {
                 var bg = tag.style.background;
                 allBackgroundURLs.push(bg.substr(bg.indexOf("url") + 4, bg.lastIndexOf(")") - (bg.indexOf("url") + 4) ) );
             }
         }
    });
    

提交回复
热议问题