How can I determine the background image URL of a div via JavaScript?

css, html, javascript

Solution

Try this:

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

Problem

I've found plenty of information on how to change the background image of a div using JavaScript, but I am trying to use JavaScript to determine which background image is being displayed. The code to set the image goes like this: ``` document.getElementById("widgetField").style.background="url(includes/images/datepicker_open.png)"; ``` I have tried every combination I can think of to access the background image url, but so far no dice: ``` alert(document.getElementById("widgetField").style.backgroundImage.url); - returns Undefined alert(document.getElementById("widgetField").style.backgroundImage); - empty response alert(document.getElementById("widgetField").style.background); alert(document.getElementById("widgetField").style.background.image); alert(document.getElementById("widgetField").style.background.url); alert(document.getElementById("widgetField").style.background.image.url); alert(document.getElementById("widgetField").style.background.value); alert(document.getElementById("widgetField").style.background.image.value); alert(document.getElementById("widgetField").style.background.image.value); alert(document.getElementById("widgetField").style.backgroundImage.value); ``` Does anyone know how to do this? Is it possible? BTW, here is the way the image is being set in CSS in the beginning: ``` #widgetField { width: 290px; height: 26px; background: url(../images/datepicker_closed.png); overflow: hidden; position: relative; } ``` UPDATE: If I run the following, it works: ``` document.getElementById("widgetField").style.background="url(includes/images/datepicker_open.png)"; alert(document.getElementById("widgetField").style.background); ``` However, I cannot seem to access the URL property until it has been set by JavaScript, even though it is already defined in the CSS file. Is there a reason why the raw CSS setting is not accessible?

Original source