Javascript: Get background-image URL of <div>

How would I get the background-image URL of a <div> element in JavaScript? For example, I have this:

<div style="background-image:url('http://www.example.com/img.png');">...</div>

How would I get just the URL of the background-image?

Answers


You can try this:

var img = document.getElementById('your_div_id'),
style = img.currentStyle || window.getComputedStyle(img, false),
bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");

// Get the image id, style and the url from it
var img = document.getElementById('testdiv'),
  style = img.currentStyle || window.getComputedStyle(img, false),
  bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");

// Display the url to the user
console.log('Image URL: ' + bi);
<div id="testdiv" style="background-image:url('http://placehold.it/200x200');"></div>

Just to add to this in case anyone else has a similar idea, you could also use Regex:

var url = backgroundImage.match(/url\(["']?([^"']*)["']?\)/)[1];

However it seems like @Praveen's solution actually performs better in Safari and Firefox, according to jsPerf: http://jsperf.com/match-vs-slice-and-replace

If you want to account for cases where the value includes quotes but are unsure whether it's a double or single quote, you could do:

var url = backgroundImage.slice(4, -1).replace(/["']/g, "");

Try this:

var url = document.getElementById("divID").style.backgroundImage;
alert(url.substring(4, url.length-1));

Or, using replace:

url.replace('url(','').replace(')','');
// Or...
backgroundImage.slice(4, -1).replace(/["']/g, "");

First of all you need to return your background-image content:

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

This will return the URL as following:

"url('http://www.example.com/img.png')"

Then you need to remove the un-wanted parts of this URL:

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

Need Your Help

Unresolved external symbol LNK2019

c++ visual-studio linker linker-errors unresolved-external

First of all, I know this question is all over this site but I have looked at almost all of them and can't seem to find out what is wrong. This is in VS 2012. Thanks.

STAThread and multithreading

c# .net multithreading sta

From the MSDN article on STAThread: