Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

174
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!