How to get background image URL of an element using JavaScript?

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>

Edit:

Based on @Miguel and other comments below, you can try this to remove additional quotation marks if your browser (IE/FF/Chrome…) adds it to the url:

bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");

and if it may includes single quotation, use: replace(/['"]/g, "")

DEMO FIDDLE

Leave a Comment