mercredi 1 mai 2019

Is there a way to select a random cell from an HTML table and change its background color?

I need to randomly select a single cell from a 5X5 table and change its background color.

I am new to programming and this one has me stumped. I have been able to successfully fill my table with string values from an array. What I need to do is randomly select one of the cells in the table and set its background color. The data in the table is static, but I want the cell that receives the background color to be random each time the page is refreshed. Help, please!

<!DOCTYPE html>
<html>

<head>
  <style>
    table,td {
      border: .25em solid black;
      border-collapse: collapse;
      text-align: center;
      padding: .5em;
    }
  </style>
</head>

<body>
  <table id="table">
  </table>

  <script>
    let table = document.getElementById("table");
    let tr;
    let td;
    let cells = ["marcaroni", "onion rings", "salad", "burger", 
"cheesecake", "sandwich", "enchiladas", "fried chicken", "soup", "pizza", 
"hot dog", "ice cream", "stew", "burrito", "crackers", "fettuccine 
alfredo", "taco", "zucchini", "sushi", "chili", "popcorn", "fried rice", 
"fruit salad", "lasagna", "dill pickles"];
    let cell;

     for (let i = 0; i < 5; i++) {
       tr = document.createElement("tr");
       for (let j = 0; j < 5; j++) {
         td = document.createElement("td");
         cell = i * 5 + j;
          td.innerText = cells[cell];
          tr.appendChild(td);
       }
       table.appendChild(tr);
     }
   </script>
 </body>

 </html>




Aucun commentaire:

Enregistrer un commentaire