Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

178
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda