4

I want to get all the html page elements' background images that are set using css or the element background property.

how can I do this using javascript?

2
  • Getting the currently-effective style for an element varies a lot between old IE versions and other browsers - this is one of those cases where a DOM framework really can save you a lot of trouble. Commented Jan 29, 2011 at 15:41
  • how can i do this using the dom framework ? Commented Jan 29, 2011 at 15:44

2 Answers 2

6

The getStyle() function below was taken from http://www.quirksmode.org/dom/getstyles.html#link7 (and slightly modified).

Of course you need to make sure the DOM is ready. An easy way to do that is to place the script toward the bottom of the page, just inside the closing </body> tag.

<script type="text/javascript">
    function getStyle(x, styleProp) {
        if (x.currentStyle) var y = x.currentStyle[styleProp];
        else if (window.getComputedStyle) var y = document.defaultView.getComputedStyle(x, null).getPropertyValue(styleProp);
        return y;
    }

       // Get all elements on the page
    var elements = document.getElementsByTagName('*');

       // store the results
    var results = [],
        i = 0,
        bgIm;

       // iterate over the elements
    for (;elements[i];i++) {
             // get the background-image style property
        bgIm = getStyle(elements[i], 'background-image');

             // if one was found, push it into the array
        if (bgIm && bgIm !== 'none') {
            results.push(bgIm);
        }
    }

       // view the console to see the result
    console.log(results);
</script>

It sounded like you want the path to the images themselves.

If you wanted the actual elements, change:

results.push(bgIm);

to:

results.push(elements[i]);
Sign up to request clarification or add additional context in comments.

1 Comment

@M.B.Asfoor: I think this will work. Give it a try. I may need to add in a fix for IE.
5

You could us jquery:

imgs = [];
$("*").each(function(i) { 
  if($(this).css("background-image") != "none") { 
    imgs.push($(this).css("background-image")); 
  } 
});

2 Comments

but mostly, I think, we use to use background than background-image
background-image should work because css() returns the computed style, so it doesn't matter how it was set.

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.