celliott1997 celliott1997 - 14 days ago 7
CSS Question

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
?

Answer

You can try this:

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

Edit:

Based on @Miguel comment below, you can try this for IE:-

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

DEMO FIDDLE

Comments