Julius Marminge
Julius Marminge

Reputation: 31

How can I get this If-statement to return true?

I am struggling to get a true return value from an if-statement.

I have debugged every possible way and I still didn't get a true return from the following if-statement:

if (document.getElementById('U1').style.background == 'white') {
   document.getElementById('U1').style.background = 'limegreen';
} else {
    document.getElementById('U1').style.background = 'blue';
  }

So, I am checking if the style background on the U1 is white, which is set in my CSS file. But, I always get a false return i.e. blue background. Does anyone know what is wrong?

Upvotes: 0

Views: 71

Answers (4)

Julius Marminge
Julius Marminge

Reputation: 31

Found a solution by first setting the style in the script and then comparing, maybe not the most efficient but it works. Here is the code:

var u1 = document.getElementById('U1');
u1.style.background = 'white';
document.getElementById('U1').addEventListener('click', function() {
  if (u1.style.background == 'white') {
    u1.style.background = 'limegreen';
  } else if (u1.style.background == 'limegreen') {
    u1.style.background = 'red';
  } else if (u1.style.background == 'red') {
    u1.style.background = 'blue';
  } else if (u1.style.background == 'blue') {
    u1.style.background = 'orange';
  } else if (u1.style.background == 'orange'){
    u1.style.background = 'yellow';
  } else if (u1.style.background == 'yellow') {
    u1.style.background = 'white';
  }
});

If you didn't understand before this lets me cycle through colours when I press a button.

Upvotes: 0

Pramod More
Pramod More

Reputation: 1

Use backgroundColor instead of background in IF condition

if (document.getElementById('demo').style.backgroundColor == 'yellow') {
document.getElementById('demo').style.background = 'limegreen';
} else {
    document.getElementById('demo').style.background = 'blue';
  }
}

Upvotes: 0

Musa
Musa

Reputation: 97672

document.getElementById('U1').style.background is going to check the style attribute on the element, not the style in style sheets or that gets rendered.
To get the style rendered you can use getComputedStyle

var u1 = document.getElementById('U1')
let compStyles = window.getComputedStyle(u1);
if (compStyles.getPropertyValue('background') == 'white') {
    u1.style.background = 'limegreen';
} else {
    u1.style.background = 'blue';
}

Upvotes: 1

user11918649
user11918649

Reputation:

Looking at your code, I assume you want to toggle the background-color. If that is the case you should use the backgroundColor instead of background property, like so:

if (document.getElementById('U1').style.backgroundColor == 'white') {
   document.getElementById('U1').style.backgroundColor = 'limegreen';
} else {
   document.getElementById('U1').style.backgroundColor = 'blue';
}

More about the backgroundColor property

Upvotes: 1

Related Questions