简体   繁体   中英

How to check if div has a specific value in JavaScript

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.

var text = document.getElementById("value").innerHTML;
if (text == "0") {
    ...

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 -----------------------------------^
<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>

FIDDLE

if you want to use jquery:

if($("#value").html() == "0") {
    $("#background").css("background-color", "red");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM