2

I'm trying to apply an if else statement to an element determining whether another element has a particular background color.

I have stated the element background color as blue in the CSS, however when I add the javascript statement, the element ignores the background color stated in the CSS (blue) and adopts the one stated in the JS IF statement (red).

HTML:

<div id="img"></div>
<div id="color">test</div>

CSS;

#img {
    background:blue;
}

JS

if (document.getElementById('img').style.background = "red")
    {document.getElementById('color').style.background = "green";} 
else {document.getElementById('color').style.background = "red";}

Does anyone know why this is happening?

JS Fiddle example

Yule
  • 9,668
  • 3
  • 51
  • 72
Gary Voss
  • 225
  • 3
  • 13
  • 2
    Instead of trying to fool the system and get around the rule of posting your code in your question when linking to jsFiddle, why not just do as you're asked to? If jsFiddle ever goes away or is inaccessible, your question loses all value to future visitors with your code in it. – j08691 Nov 23 '15 at 14:47

1 Answers1

1

The issue here is:

if (document.getElementById('img').style.background = "red")

You're actually resetting the CSS - not saying if it's equal to - try the following:

if (document.getElementById('img').style.background == "red")
{document.getElementById('color').style.background = "green";} 
else {document.getElementById('color').style.background = "red";}

The operator == is how you'd check if something is equal to something else, or you can use === if you want to make sure the type is also the same. A good explanation of the two operators can be found here: Which equals operator (== vs ===) should be used in JavaScript comparisons?

Community
  • 1
  • 1
Aravona
  • 528
  • 6
  • 21