0

I want to check what the background image is in Javascripot. I tried to do this:

if (document.getElementById(id).style.backgroundImage == "image.jpg") {
    //code
}

but that doesn't work. Is this possible?

CPC
  • 163
  • 5
  • 17

2 Answers2

0

The backgroundImage property in javascript uses the CSS syntax.

So, to test for the background image, you would test against url('image.jpeg').

Try this:

if (document.getElementById(id).style.backgroundImage == "url('image.jpg')") {
    //code
}
Leroy
  • 544
  • 3
  • 14
0

A more appropriate test, to make sure you're not getting type errors too:

var backImgUrlTest = function(elem, imgUrl){ 
  return elem && elem.backgoundImage.replace(/^url\(('|")|('|")\)$/g, "") === imgUrl;
};

if(backImgUrlTest(document.getElementById(id), "image.jpg")){
    /* Code here */
}
Andrew Templeton
  • 1,656
  • 10
  • 13