96

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

Is it possible?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
jQuerybeast
  • 14,130
  • 38
  • 118
  • 196
  • Does this answer your question? [Get URL from background-image Property](https://stackoverflow.com/questions/6397529/get-url-from-background-image-property) – Jason C Sep 08 '20 at 16:23

9 Answers9

201

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);
    });
Moritz Pfeiffer
  • 447
  • 1
  • 7
  • 23
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • 4
    What if the background image URL is something like `url(my%20picture%20Copy\(1\).jpg)`? Your replace cause the bg variable to be `my%20picture%20Copy\(1\.jpg)`. It also doesn't strip quoting (e.g. `url("the picture.jpg")`). – Benjamin Manns Feb 05 '13 at 17:31
  • 1
    Then you'll either have to add some code to un-escape the `%20` and parentheses, or ask yourself if you really needed them there in the first place. If quoting in an issue, use [RobW](http://stackoverflow.com/a/8809891/901048)'s solution instead. – Blazemonger Feb 05 '13 at 17:33
  • 1
    Doesn't handle multiple background images as a possibility. – Marcel Aug 15 '14 at 02:22
  • 1
    @Marcel Easy if you just have images; just split the string on commas. Trickier if you have things like [linear gradients](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_multiple_backgrounds) in there, since those also have commas. – Blazemonger Aug 15 '14 at 13:09
  • `var bg = $(this).css('background-image').slice(4).slice(0,-1)` ;) – Samuel Katz Jan 12 '15 at 17:16
  • Doesn't work in Firefox! Take a look at MoMolog for a more complete and cross-browser Regex, that takes in account all the possibilities for "url( [...] )", with single and double quotes. – caulitomaz Jul 07 '15 at 18:29
  • 2
    this won't work if the background-image is something like `background-image:linear-gradient(rgba(0,0,0,0.2), rgba(0,0,0,0.4)), url("https://mdn.mozillademos.org/files/7693/catfront.png")` – glasspill Feb 17 '16 at 15:33
  • @glasspill Yes, I already said that when Marcel pointed it out. Something like that requires a more intelligent parser that can split on the correct commas, but OP didn't require such a thing. – Blazemonger Feb 17 '16 at 17:32
55

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);
});
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • I want to alert it not to set it. Alert or write the path on console.log – jQuerybeast Jan 10 '12 at 20:14
  • to write on console try : console.log($('#div1').css('background-image')) – Mandeep Pasbola Jan 10 '12 at 20:18
  • @RobW Thank you. That prints url(google.com) instead of just the domain – jQuerybeast Jan 10 '12 at 20:18
  • @jQuerybeast My code is not setting the CSS. The `.css` method returns the value of a property, when invoked with one argument. – Rob W Jan 10 '12 at 20:18
  • Cannot call method match. Shall I turn it into regEx? – jQuerybeast Jan 10 '12 at 20:22
  • Try: `bg_url = /^url\(['"](.+)["']\)$/.exec(bg_url);`, to be safe. – Rob W Jan 10 '12 at 20:37
  • Could this be modified so that it can accept a url with or without quotes? At present I get an error if my url is: url(http://www.example.com/image.jpg) – GuyC Apr 16 '13 at 12:48
  • @Lopsided Show an example where a background image is loaded through `url` and this method fails. Are you sure that the element you're targeting has a background image? Is it really an external image and not something like a CSS gradient? – Rob W Jul 13 '13 at 20:54
  • @RobW awe damn I just deleted the script. Sorry, I had to move on anyway. I'll get it going another way. – Ross Brasseaux Jul 13 '13 at 20:58
  • @RobW is that faster then `bg.replace('url(','').replace(')','');`? – Leon Aug 03 '13 at 12:48
  • 2
    @tim No, it's just more accurate. Imagine: `background-image: url('photo(2012).png');` With your bit of code, you'll get "'photo(2012.png')", which is obviously incorrect. – Rob W Aug 03 '13 at 12:50
22

I have slightly improved answer, which handles extended CSS definitions like:

background-image: url(http://d36xtkk24g8jdx.cloudfront.net/bluebar/359de8f/images/shared/noise-1.png), -webkit-linear-gradient(top, rgb(81, 127, 164), rgb(48, 96, 136))

JavaScript code:

var bg = $("div").css("background-image")
bg = bg.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '')

Result:

"http://d36xtkk24g8jdx.cloudfront.net/bluebar/359de8f/images/shared/noise-1.png"
Michael Spector
  • 36,723
  • 6
  • 60
  • 88
  • this won't work if the background-image is something like background-image:linear-gradient(rgba(0,0,0,0.2), rgba(0,0,0,0.4)), url("https://mdn.mozillademos.org/files/7693/catfront.png") – glasspill Feb 17 '16 at 15:34
10

As mentioned already, Blazemongers solution is failing to remove quotes (e.g. returned by Firefox). Since I find Rob Ws solution to be rather complicated, adding my 2 cents here:

$('#div1').click (function(){
  url = $(this).css('background-image').replace(/^url\(['"]?/,'').replace(/['"]?\)$/,'');
  alert(url);
})
Alexander Presber
  • 6,429
  • 2
  • 37
  • 66
6

I'm using this one

  function getBackgroundImageUrl($element) {
    if (!($element instanceof jQuery)) {
      $element = $($element);
    }

    var imageUrl = $element.css('background-image');
    return imageUrl.replace(/(url\(|\)|'|")/gi, ''); // Strip everything but the url itself
  }
Berty
  • 1,081
  • 1
  • 18
  • 49
6

I think that using a regular expression for this is faulty mainly due to

  • The simplicity of the task
  • Running a regular expression is always more cpu intensive/longer than cutting a string.

Since the url(" and ") components are constant, trim your string like so:

$("#id").click(function() {
     var bg = $(this).css('background-image').trim();
     var res = bg.substring(5, bg.length - 2);
     alert(res);
});
Middletone
  • 4,190
  • 12
  • 53
  • 74
4

Here is a simple regex which will remove the url(" and ") from the returned string.

var css = $("#myElem").css("background-image");
var img = css.replace(/(?:^url\(["']?|["']?\)$)/g, "");
1

Using just one call to replace (regex version): var bgUrl = $('#element-id').css('background-image').replace(/url\(("|')(.+)("|')\)/gi, '$2');

Ogg
  • 59
  • 7
0

My two cents.
None of these solutions work if the background-image property is overwritten in CSS by the background property.
Let's say you have the background-image property set and you don't want to see it in the browser, you just need to get the value in jQuery for some purpose. So, if you have something like this:

<div class="myDivWithBackground">
 <p>Lorem Ipsum</p>
</div>
<style>
.myDivWithBackground{
 background-image: URL('url-here.jpg')
}
div.myDivWithBackground{
 background: #fff!important
}
</style>

Then $('div').css('background-image'); returns none instead the URL.

If you need to keep background white and also to get the background-image URL value in jQuery then replace the background with pseudo-element, like this:

<style>
    .myDivWithBackground{
     background-image: URL('url-here.jpg')
    }
    div.myDivWithBackground:after{
      content: '';
      display: block;
      width: 100%;
      height: 100%;
      background: #fff;
      top: 0;
      position: absolute;
    }
    div.myDivWithBackground p{
      position: relative;
      z-index: 9999;
    }
</style>

Now $('div').css('background-image'); returns URL('url-here.jpg') instead none.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Alexandru Burca
  • 427
  • 1
  • 4
  • 15