samedi 5 mai 2012

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.

Aucun commentaire:

Enregistrer un commentaire