First of all, I am beginner in programming. I've got a question qbout JavaScript DOM. I would like to check if a tag or node has a backgroundColor style in order to execute the rest of the code, I also tried to put .clicked property but it doesn't work. Here's my code:
let btn1 = document.getElementById("0");
let btn2 = document.getElementById("1");
btn1.addEventListener("click", function() {
btn1.style.backgroundColor = 'red';
btn2.style.backgroundColor = 'green';
});
if (btn1.style.background == 'red' || span2.style.backgroundColor == 'red') {
console.log("test"); // doesn't work !!
}
It because your if
statement only runs once. Wrap it inside a function and call that function after each click:
let span1 = document.getElementById("0").getElementsByTagName("span")[1];
let span2 = document.getElementById("0").getElementsByTagName("span")[2];
span1.addEventListener("click", function () {
span1.style.backgroundColor = "gray";
span2.style.backgroundColor = "#eee";
checkColor();
});
span2.addEventListener("click", function () {
span2.style.backgroundColor = "gray";
span1.style.backgroundColor = "#eee";
checkColor();
});
function checkColor() {
if (
span1.style.backgroundColor == "gray" ||
span2.style.backgroundColor == "gray"
) {
console.log("test"); // doesn't work !!
}
}
<ul id="questions">
<li id="0">
<span>Do you like JavaScript?</span>
<span>Yes</span><span>No</span><span class="result"></span>
</li>
<li id="1">
<span>JavaScript and Java are the same</span>
<span>Yes</span><span>No</span ><span class="result"></span>
</li>
<li id="2">
<span>JavaScript is easy to learn</span>
<span>Yes</span><span>No</span><span class="result"></span>
</li>
</ul>
Note: this snippet only includes the first 2 spans.