Can someone tell me what I am doing wrong here? What I am trying to do is looping through the list and assign a background colour for odd and even numbers.
Thanks in advance.
var box = document.querySelectorAll('.links-wrapper li'); for(var i = 0; i < box.length; i++){ if(box[i] % 2 === 0){ box[i].style.backgroundColor = 'red'; } else { box[i].style.backgroundColor = 'blue'; } }
Change box[i]
to i
for(var i = 0; i < box.length; i++){
if(i % 2 === 0){
box[i].style.backgroundColor = 'red';
} else {
box[i].style.backgroundColor = 'blue';
}
}
Else you can use css psuedo selector
.links-wrapper li:nth-child(even) { color: red } .links-wrapper li:nth-child(odd) { color: green }
<ul class="links-wrapper"> <li> 1</li> <li> 2</li> <li> 3</li> <li> 4</li> <li> 5</li> </ul>
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.