Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
Running js function on table

How do I make it change each element to a random color instead of changing all the elements to the same random color

function RandomColor() {
const randomColor = Math.floor(Math.random()*16777215).toString(16);
var th = document.getElementsByTagName('th');
for (i = 0; i < th.length; i++) {
    x = th[i]
x.style.backgroundColor = "#" + randomColor;
    }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You need to set the random color in the iteration so it resets for every element.

function RandomColor() {
  var th = document.getElementsByTagName('th');
  for (i = 0; i < th.length; i++) {
    const randomColor = Math.floor(Math.random() * 16777215).toString(16);
    x = th[i]
    x.style.backgroundColor = "#" + randomColor;
  }
}

RandomColor();
<table>
  <tr>
    <th>Lorem</th>
    <th>Ipsum</th>
  </tr>
  <tr>
    <td>foo</td>
    <td>bar</td>
  </tr>
</table>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!