Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

90
Visualizações
Apply color to clicked table row

i have this function to detect when i click on a table row. I want it to turn the clicked on row a certain colour and remove the active class from all other rows. Currently it just makes every row i click on red without removing the colour from the other rows.

html:

var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
var tbodyRows = table.getElementsByTagName("tr")[0];

tbody.onclick = function (e) {
    e = e || window.event;
    var target = e.srcElement || e.target;
    while (target && target.nodeName !== "TR") {
        target = target.parentNode;
    }
    tbodyRows.classList.remove('active');
    target.classList.add('active');
}

js:

<table id="data">
    <thead> 
        <tr>
            <th class="number" style="text-align:center">#</th>
            <th class="time" style="text-align:center">time</th>
            <th class="artist">artist</th>
            <th class="song">song</th>
        </tr>
    </thead>

    <tbody id="song-data"></tbody>

</table>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

This should work. Notice how tBodyRows now references all table rows (removed the [0]) and how we iterate over it with forEach().

var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
var tbodyRows = table.getElementsByTagName("tr");

tbody.onclick = function (e) {
    e = e || window.event;
    var target = e.srcElement || e.target;
    while (target && target.nodeName !== "TR") {
        target = target.parentNode;
    }    

    Array.from(tbodyRows).forEach(elem => {
        elem.classList.remove('active')
    })
    
    
    target.classList.add('active');
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You aren't possible to remove all the color from the other rows, because you are not deleting the other rows classes, you are only deleting one, I think a better way to show you is doing it, so I did this (I also think you can refactor a little more):

const table = document.getElementById('data');
let tableBody = table.querySelector('tbody');

tableBody.onclick = function (e) {
    let tableRows = table.querySelectorAll('tbody tr');
    let target = e.target.parentNode;
    
    while (target.nodeName !== 'TR') {
      target = target.parentNode;
    }
    
    tableRows.forEach((element) => {
      element.classList.remove('active');
    });
    
    target.classList.add('active');
}
.active {
  background-color: red;
}
<table id="data">
    <thead> 
      <tr>
        <th class="number" style="text-align:center">#</th>
        <th class="time" style="text-align:center">time</th>
        <th class="artist">artist</th>
        <th class="song">song</th>
      </tr>
    </thead>

    <tbody id="song-data">
      <tr>
        <td>A</td>
        <td>B</td>
        <td>C</td>
        <td>D</td>
      </tr>
      <tr>
        <td>A</td>
        <td>B</td>
        <td>C</td>
        <td>D</td>
      </tr>
    </tbody>
</table>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda