Wednesday, July 08, 2009

jQuery Quick Tip: Extract CSS Background Image

jQuery allows you to get the background image of any element on a web page:

$("#myelement").css("background-image");

However, this returns it in an undesirable format: url(http://example.com/images/image.jpg) or url("http://example.com/images/image.jpg"). With a bit of string replacement, you can get extract the URL:

function extractUrl(input)
{
 // remove quotes and wrapping url()
 return input.replace(/"/g,"").replace(/url\(|\)$/ig, "");
}

So now you can just do this:

extractUrl($("#myelement").css("background-image"))

Which will return the URL on its own http://example.com/images/image.jpg.

2 comments:

Renowned Media said...

Regular expressions to the rescue!

H. K. Nuhu said...

This seems to be a very useful blog for a web developer like me. I have been using jQuery and your blog site has some useful info. Thanks.