Reputation: 197
Short and sweet, can this be run?
if ( document.getElementById('box').style.background = "red") {
document.getElementById('box').style.background = "yello"
} else {
document.getElementById('box').style.background = "green"
}
The Problem
So lets say a box, with an ID of "box", has conditions run prior to the statement above, that changes the background to red, can the if statement then change the box background to yellow? This may be confusing, but in short, can you use a CSS style condition, to run a block of javascript, to then change the css of that element?
Upvotes: 0
Views: 138
Reputation: 1646
if (document.getElementById('box').style.backgroundColor === "red") {
document.getElementById('box').style.backgroundColor = "yellow"
} else {
document.getElementById('box').style.backgroundColor = "green"
}
#box {
width: 100px;
height: 100px;
background: red;
}
<div id="box" style="background-color: red;" ></div>
Upvotes: 0
Reputation: 1183
I think the answer is yes. But your assignment is not right i guess. What you mean is check background color is currently red then change it to yellow? I tested in a jsfiddle: https://jsfiddle.net/r3y72njf/24/. You can also check here: https://www.w3schools.com/jsref/prop_style_backgroundcolor.asp. One more thing, in your comparison, you must use '==' or '===', '=' mean assignment.
if ( document.getElementById('box').style.backgroundColor === "red") {
document.getElementById('box').style.backgroundColor = "yelloy"
} else {
document.getElementById('box').style.backgroundColor = "green"
}
Upvotes: 6
Reputation: 7506
Simply add a id="box"
attribute to any visible elements on any pages to make a test.
E.g.
In the element and console tab of Chrome devtool:
Add id="box"
to this question's title.
set its background and get the return value.
var c = document.getElementById('box').style.background = "red"
. And c is "red"
. Use typeof c
, c is a string
.
So your answer is yes because you can use a string
as a condition. But be aware of that you may get TypeError
if the target element with id="box"
does not exist.
Upvotes: 0