0

I use attr('style') and able to get below's value,

background-image: url(http://example.com/img/123456-bg.jpg); background-size: cover;

but how to proceed to get

123456-bg
Alice Xu
  • 533
  • 6
  • 20
  • What about .css(element) . – BenB Jul 09 '15 at 03:41
  • 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

5 Answers5

1

Try

var $div = $('#mydiv'),
  bimg = $div.css('background-image');
var match = bimg.match(/\d+-bg/),
  value = match ? match[0] : undefined;

snippet.log(value)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<!-- To show result in the dom instead of console, only to be used in the snippet not in production -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="mydiv" style="background-image: url(http://example.com/img/123456-bg.jpg); background-size: cover;"></div>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

More or less like this: http://jsfiddle.net/stdob/52ok19gr/3/

var url = $("#div").css('background-image');

var m = new URL(url.match(/url\((.*)\)/).pop());

m.filename = (m.pathname).substring( (m.pathname).lastIndexOf('/')+1 );

m.basename = m.filename.match(/(.*)\.(.*)/)[1];

console.log(m);
stdob--
  • 28,222
  • 5
  • 58
  • 73
0

Use this instead

'.css("background-image")'

Mindastic
  • 4,023
  • 3
  • 19
  • 20
0

Try this...

var index = yourUrl.lastIndexOf("/") + 1;
var img = yourUrl.substr(index);
var imgName = img.substr(0, img.indexOf('.'));
alert(imgName);
John R
  • 2,741
  • 2
  • 13
  • 32
0

This should work:

var imageName = $('#yourDiv').css('background-image').match(/img\/(.*)\.jpg/)[1];
leo.fcx
  • 6,137
  • 2
  • 21
  • 37