Reputation:
I want to know how I can let the JavaScript react when the div has a certain value.
<div id="background">
<div id="value">1</div>
</div>
<script>
var text = document.getElementById("value");
if (text = "0") {
document.getElementById("background").style.backgroundColor="red";
}
</script>
If the value div has 0, I want the background color to be red of the div called background. If the value div has a other value, it should do nothing. This is what I've come up to. But it don't work. Even if I put another value in the value div, the red background still shows. Except when I emptied the value div, then ofcourse you will see nothing.
Upvotes: 0
Views: 5564
Reputation: 3397
if you want to use jquery:
if($("#value").html() == "0") {
$("#background").css("background-color", "red");
}
Upvotes: 1
Reputation: 3606
<div id="background">
<div id="value">1</div>
</div>
<script>
var text = document.getElementById("value").innerHTML;
if (text == "0") {
document.getElementById("background").style.backgroundColor="red";
}
</script>
Upvotes: 2
Reputation: 1074138
The comparison operators in JavaScript are ==
and ===
, not =
(that one is always assignment). So:
if (text == "0") {
or
if (text === "0") {
You're also not getting the text correctly:
var text = document.getElementById("value");
That gives you the element, not its contents. For contents, use innerHTML
.
var text = document.getElementById("value").innerHTML;
// Here -----------------------------------^
Upvotes: 6
Reputation: 8169
var text = document.getElementById("value").innerHTML;
if (text == "0") {
...
Upvotes: 6