Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get div's background-image url?

I have a button of which when I click it I want to alert the background-image URL of #div1.

Is it possible?

like image 756
jQuerybeast Avatar asked Jan 10 '12 20:01

jQuerybeast


2 Answers

I usually prefer .replace() to regular expressions when possible, since it's often easier to read: http://jsfiddle.net/mblase75/z2jKA/2

    $("div").click(function() {         var bg = $(this).css('background-image');         bg = bg.replace('url(','').replace(')','').replace(/\"/gi, "");         alert(bg);     }); 
like image 140
Blazemonger Avatar answered Sep 28 '22 19:09

Blazemonger


Yes, that's possible:

$("#id-of-button").click(function() {     var bg_url = $('#div1').css('background-image');     // ^ Either "none" or url("...urlhere..")     bg_url = /^url\((['"]?)(.*)\1\)$/.exec(bg_url);     bg_url = bg_url ? bg_url[2] : ""; // If matched, retrieve url, otherwise ""     alert(bg_url); }); 
like image 28
Rob W Avatar answered Sep 28 '22 20:09

Rob W