-1

I have a div that I want to change color based on the int value in the div, but for some reason it doesn't change the color based on the if else statement I wrote. Instead no color appears. Why is that?

<div id="test">66</div>

JAVASCRIPT

var testDiv = document.getElementById("test");

if (testDiv<50) {
    testDiv.style.backgroundColor = '#900000';
} else if (testDiv > 49 && testDiv < 75) {
    testDiv.style.backgroundColor = '#FF9933';
} else if (testDiv > 74) {
    testDiv.style.backgroundColor = '#00CC00';
}
2
  • 2
    Why would testDiv be a number, or in any way comparable to a number, it's clearly an element Commented Feb 5, 2015 at 22:51
  • You probably want parseInt( testDiv.innerHTML, 10) Commented Feb 5, 2015 at 22:52

3 Answers 3

4

You're treating the element like a number. You want to retrieve the element's content and convert it to a number.

var testDivValue = parseInt(testDiv.textContent, 10);
Sign up to request clarification or add additional context in comments.

Comments

1

You are trying to check the element's innerHTML but comparing with the element itself. Try:

var testDiv = document.getElementById("test");
var value = parseInt(testDiv.innerHTML);
if(value<50){
    testDiv.style.backgroundColor = '#900000';
}
else if(value>49 && value <75){
    testDiv.style.backgroundColor = '#FF9933';
}
else if(value>74){
    testDiv.style.backgroundColor = '#00CC00';
}

Comments

0

You've passed the HTML object into the if statement instead of it's actual value. You can use innerHTML property in order to get the content within the HTML element.

var test = document.getElementById("test"); // element by id
var testContent = test.innerHTML;           // the value of inner HTML content

Once you have stored the value in testContent variable, you can do whatever you want with it ;-)

    // Check if value of inner HTML is less than 50
    if(testContent < 50) {
      alert("true, do whatever you want.");
    } else {
      alert("false");
    }

I hope you find this useful,

Thanks.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.