<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"?
.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;
}