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.
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.
//alert(getallBgimages())
One of the way is to look through all document object and get there styles. Then test style.background attribute on "url(" string and if it matches then get path between "url(" and ")" and put it into array. Algorithm for JS. Try to do it yourself. Will find troubles - came with code.
Without using jQuery, you can do:
Here's a way to check what background urls there are in the styles on the page (look Ma, no jQuery):
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<style>
tags on the page are scavenged.The routine is easy to modify if you would like to keep a count, or keep associations to the actual rules that an url was found in etc.
I needed this function, but they were all too heavy unfortunately. So thinking about it, here is my solution, if it can help.
Does not work for background image in external stylesheet.
This is a complicated problem. The reason is that the background-image can be applied to the element by using a separate CSS file. This way parsing all the objects in the DOM and checking for their background-image will not work.
One of the ways I can see is to create a simple HttpHandler which will work on all the type of images. When images are referenced inside the CSS file they are downloaded as a separate entity. This means HttpHandler will be able to capture the type of the image and then execute on it.
Maybe a server side solution is the best way to go on this one!