For example with a div
element, this code works:
function col() {
document.getElementById('myID').style.backgroundColor = // ...
How can I do this for all even rows? This does not work:
function col() {
document.querySelectorAll("tr:nth-child(even)").style.backgroundColor = // ...
2
Answers
The issue is because
querySelectorAll()
returns a Collection of elements, not a single Element. Therefore you need to loop over them all and set their background individually:Here’s some further reading for you on this subject.
With that being said, you should not be using JS to update the UI. Use CSS instead, where possible.
The reason the code
document.querySelectorAll("tr:nth-child(even)")
doesn’t work is becausedocument.querySelectorAll()
returns aNodeList
, which is a collection of elements, not a single node as it is case withdocument.getElementById
. You cannot directly set the style of a COLLECTION of elements. Instead, you need to loop through each element in the NodeList and apply the style individually.This might help