0

I have a load of images in the DOM, where the images href is set in CSS.

Anyone know a fairly good way to pull out a list of all of these much like

document.images

This pulls out an array of image tags.

I need to do a similar thing but pull out all image urls that might be located in CSS Classses

I need to do a replace on certain images using JavaScript

Welsh King
  • 3,178
  • 11
  • 38
  • 60

2 Answers2

3

You can:

  1. Loop through the stylesheet objects in document.styleSheets
  2. For each stylesheet (a CSSStyleSheet), loop through its cssRules (old IE uses rules rather than cssRules)
  3. For each rule (a CSSRule) that has a style property, loop through that style object's properties and, of those that are strings and have the target image, do your replacement.

Example replacing my Gravatar with yours after one second:

setTimeout(function() {
  var rexOldImage = /ca3e484c121268e4c8302616b2395eb9/g;
  var newImage = "fe10f9831fc5d88da31dab172740a1ad";
  var slice = Array.prototype.slice;
  slice.call(document.styleSheets).forEach(function(styleSheet) {
    slice.call(styleSheet.cssRules || styleSheet.rules).forEach(function(rule) {
      var name, style;
      if (rule.style) { // Only CSSStyleRules have a style prop
        for (name in rule.style) {
          style = rule.style[name];
          if (typeof style === "string" && rexOldImage.test(style)) {
            rule.style[name] = style.replace(rexOldImage, newImage);
          }
        }
      }
    });
  });
}, 1000);
.some-class {
  background-image: url(https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=32&d=identicon&r=PG);
  width: 32px;
  height: 32px;
}
<div class="some-class"></div>

If that use of slice is unfamiliar, see the "array-like objects" part of this answer.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I have picked one of the style sheets document.styleSheets[0].rules[0]; and the rules text is "@import url("layout.css");" – Welsh King Dec 09 '15 at 12:44
  • @WelshKing: I suspect you'll find the styles from the imported sheet either as a separate sheet object, or as rules in that same sheet object. Sadly, `cssText` is read-only, so we have to work harder -- see the updated answer. – T.J. Crowder Dec 09 '15 at 12:53
  • perfect solution - couldn't explain it better :) – jebbie Dec 09 '15 at 12:59
0

You could ajax load the css file in javascript with a get call then use regex matching to find the urls in the css. You would want to dedupe too incase of duplications but that's also possible.

Let me know if you need code to help.

Richard
  • 21,728
  • 13
  • 62
  • 101