I am trying to modify the background color of a list item, but I am encountering an issue with an if-statement. When I remove the if-statement and directly set the background color, it works fine. However, when the if-statement is included, it fails to work as expected. I need some assistance in understanding why this is happening.
HTML
<ul id="testList"> Test List
<li id="item1">Item 1</li>
<li id="item2">Item 2</li>
</ul>
CSS
#testList {
width: 100px;
background-color: grey;
margin: 200px 0px 0px 50px;
list-style-type: none;
}
#testList li {
color: black;
padding: 10px;
border: 1px solid black;
}
#testList li:hover{cursor: pointer;}
#item1 {background-color: white;}
Javascript
var item1 = document.getElementById('item1');
function setColor(){
if (item1.style.backgroundColor == 'white'){
item1.style.backgroundColor = 'green';
} else if (item1.style.backgroundColor == 'green'){
item1.style.backgroundColor = 'white';
}
}
item1.addEventListener('click', function(){setColor()}, false);