[英]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.我用 php 生成 html,就像上面的那样,当我单击“显示更多”/“添加”图标时,我想将 div.show-more-retracted 元素的类更改为 show-more-expanded。
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.还会生成 Id,我将 Id 作为参数提供给 showReligion() 函数,因为我使用 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')
我总是遇到
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.我意识到这段代码只会改变“显示更多”所在的 span 元素的类。
How can I change the class from "show-more-retracted" to "show-more-expanded"?如何将课程从“show-more-retracted”更改为“show-more-expanded”?
.nextElementSibling
to get next element and .className
to get/set the class .nextElementSibling
获取下一个元素和.className
获取/设置类
function showReligion(id) {
var element = document.getElementById(id);
element.nextElementSibling.className ="show-more-expanded";
}
to toggle between show-more-retracted
and show-more-expanded
在
show-more-retracted
和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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.