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

175
Visualizações
How can I change classes on click of php generated elements?
<tr>
    <td>Guinea-Bissau</td>
    <td>1151330</td>
    <td>36120</td>
    <td>
        <span class='show-more' onclick='showReligion(79)' id="79">Show more
        <i class='material-icons icon'>add</i></span>

        <div class='show-more-retracted'>
            Christian<br>
            Muslim<br>
        </div>
    </td>
</tr> 

I generate html, with php, like the one above and I want to change the class of the div.show-more-retracted element to show-more-expanded, when I click "show more"/the "add" icon.

The Id's are also generated and I give the Id as an argument to the showReligion() function and that works, since I checked it with console.log.

I tried it with

function showReligion(id) {
    var element = document.getElementById(toString(id));
    element.classList.toggle("show-more-expanded");
}

I always got Uncaught TypeError: Cannot read properties of null (reading 'classList')

I realized that this code would only change the class of the span element where the "Show more" is located in.

How can I change the class from "show-more-retracted" to "show-more-expanded"?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

.nextElementSibling to get next element and .className to get/set the class

function showReligion(id) {
    var element = document.getElementById(id);
    element.nextElementSibling.className ="show-more-expanded";
}

to toggle between show-more-retracted and show-more-expanded

function showReligion(id) {
  var element = document.getElementById(id).nextElementSibling;
  var newClass = element.className.includes("retracted") ? "show-more-expanded" : "show-more-retracted";
  element.className = newClass;
}
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