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

1
  • You mean you want to get all the images which have a class which is in css? Commented Dec 9, 2015 at 12:41

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I have picked one of the style sheets document.styleSheets[0].rules[0]; and the rules text is "@import url("layout.css");"
@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.
perfect solution - couldn't explain it better :)
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.