-4

I want to get the background image in a div using jquery. I tried

var img = $('#id').attr('src');

but

alert(img) 

shows up as null / undefined.

I tried this too document.getElementById('elementId').src; but same result.

I also tried this var img = $('#outer').css('background-image'); shows up as url(s/bg.jpg)

What is wrong here?

Dominique
  • 1,080
  • 14
  • 29
X10nD
  • 21,638
  • 45
  • 111
  • 152
  • Do you want the background image (as in, image set by css `background`) or an actual image tag? – soktinpk Nov 02 '14 at 17:50
  • Weird how you had an extra question (which you should have put as an edit to your original question) and then accepted the answer not addressing that extra question. This website is more than a platform for you asking questions; it's also a reference! – Dominique Nov 02 '14 at 18:13

2 Answers2

5

background-image is a CSS property, so use the .css method:

var img = $('#id').css('background-image');

The call above will return the computed style property (containing url(path)). To remove the url part use a regex replace:

img = img.replace(/^url\(|\)$/g, "");

You can do it one-line as follows:

var img = $('#id').css('background-image').replace(/^url\(|\)$/g, "");

.css( propertyName )

Get the computed style properties for the first element in the set of matched elements.

Community
  • 1
  • 1
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
  • I'm afraid you're missing some brackets. I haven't tested it but it's kinda dangerous not telling jquery what function to execute first... it's far from fail-safe! – Dominique Nov 02 '14 at 18:15
  • @Dominique I tested it. ;-) `$('#id')` is the first call, returning the jQuery object. `css(...)` is the second call (a method of the jQuery object returned by the first call) -- this returns a string, supposing the element exists. `replace(...)` is the third call using the string returned by `css`. Is it clearer? :-) – Ionică Bizău Nov 02 '14 at 18:19
  • Of course it is... and it should work... but I had some nasty experiences in the past with jquery so I started using extra brackets as a fail-safe. Maybe the later versions of jquery got better at it but in the past I can assure you the logic was lost from time to time. But hey, if what you wrote works then there's no need for the brackets... I would still use them though, but that's just me... I don't trust jquery much further than I can throw it. – Dominique Nov 02 '14 at 18:24
  • @Dominique It's not a jQuery thing but JavaScript. But I agree there are cases when additional brackets make the code clearer. – Ionică Bizău Nov 02 '14 at 18:31
  • @X10nD Yeah, since you asked how to remove `url(...)` from string and I replied, I don't feel very well to have this feedback. – Ionică Bizău Nov 04 '14 at 15:56
-1

you need to get a style property using css()

Try

var img = $('#id').css('backgroundImage');
charlietfl
  • 170,828
  • 13
  • 121
  • 150