skip to Main Content

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


  1. 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:

    document.querySelectorAll("tr:nth-child(even)").forEach(tr => tr.style.backgroundColor = '#C00');
    

    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.

    tr:nth-child(even) {
      background-color: #C00;
    }
    
    Login or Signup to reply.
  2. The reason the code document.querySelectorAll("tr:nth-child(even)") doesn’t work is because document.querySelectorAll() returns a NodeList, which is a collection of elements, not a single node as it is case with document.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

    function col() {
      const evenRows = document.querySelectorAll("tr:nth-child(even)");
      
      // Loop through each row and apply the background color
      evenRows.forEach(row => {
        row.style.backgroundColor = "yourColorHere"; 
      });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search