skip to Main Content

i have a problem with table

<td id="1" onclick="func1()">1</td> 
<td id="2" onclick="func1()">2</td> 
<td id="3">3</td> <td id="4">4</td> 
<td id="5">5</td>

and i want to change color in one cell without give another id to cell and type x5 this same function to another cell, okay, this is a js code:

function func1() {
  let table = document.querySelector("td");     
  alert("pole" + table + "nacisniete");      
  table.style.backgroundColor = "grey"; 
}

if i clicked cell 2, cell1 change color, i want to have 1 function and this must change a color in selected cell

Sorry for my english, im form poland

i want to write another id to another cell and i must have a 25 functions for this work, so i pick queryselector to pick a one cell but this dont work, i picked cell2 and change color to cell1enter image description here

2

Answers


  1. Instead of using a function on each TD, I’m using document.querySelectorALL to loop through the TDs and give each an event listener. Also, I’m adding a class instead of changing it in javascript as this will give you more options down the road. I commented out two lines these lines will remove the background on a td that has already been clicked so only one can be clicked at a time. You don’t need that but I wasn’t sure if that was what you wanted or not.

    let tds = document.querySelectorAll("td");
    tds.forEach((td) => {
      td.addEventListener("click",() =>{
         //let active = document.querySelector("td.active");
         //if(active) active.classList.remove("active");
         td.classList.add("active");
      });
    });
    td.active{
      background:gray
    }
    <table border="1" width="100%">
    <tr>
    <td>1</td> 
    <td>2</td> 
    <td>3</td> <td>4</td> 
    <td>5</td>
    </tr>
    </table>
    Login or Signup to reply.
  2. Add event listener to the parent element: "myTable" and use event.target to add class to the currently clicked cell

    const table = document.getElementById("myTable");
    
    table.addEventListener("click", (event) => {
     console.log(event.target);
     event.target.classList.add("active");
    });
    td {
      padding: 10px;
      text-align: center;
      background-color: green;
    }
    
    td.active{
     background-color:grey
    }
    
    td:hover {
      background-color:yellow;
    }
      <table id="myTable">
        <tr>
          <td>1</td>
          <td>2</td>
        </tr>
        <tr>
          <td>3</td>
          <td>4</td>
        </tr>
      </table>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search