I am working on a small project and it is my first so, I have some difficulties to get over. I am creating a dynamic list for a filtered search and the problem is that I try to add elements with php and I want them to change visibility onclick and for that I use a css code which is fully functional but the problem is with the javascript which tells me:
script.js:4 Uncaught TypeError: Cannot read property 'classList' of null at visibilityToggle (script.js:4) at HTMLDivElement.onclick (afficherDept.php:4)
js_Code:
function visibilityToggle(id) {
var section = document.getElementById(id);
section.classList().toggle("showen");
}
and this is the php code for adding elements: ---$sectionID is controlled by a loop
echo '<div onclick="visibilityToggle('.$sectionID.');"id='.$id.'>'.'ID
'.$dept["id"].'. NOM:'. $dept["nom"].'.CHEF:'.$dept["chef"].'</div>';
echo '<section class="hidden" id=' . $sectionID . '>';
It makes no sense to call a function with onclick
from an element, and then use document.getElementById
to search for the same element again...
Instead I would add a class to your divs in PHP, and use javascript to add a click handler. This way you know who called the handler and you can toggle the CSS class directly. (note: haven't tested this but I hope the idea is clear)
PHP
echo '<div class="clickablediv">simple example</div>';
JAVASCRIPT
let clickableDivs = document.getElementsByClassname("clickablediv")
for(let d of clickableDivs){
d.addEventListener("click", visibilityToggle)
}
function visibilityToggle(e) {
e.target.classList().toggle("showen");
}
The cause for the denoted error is the wrongful rendering of the html markup from your php code.
You need to put quotes around the argument passed to the visibilityToggle
function.
'<div onclick="visibilityToggle(\''. $sectionID. '\')"'
Next, the classList is a DOMTokenList
object - not a function.
So, you should access the toggle
property like this:
section.classList.toggle("showen");
thanks for all your answers.
I fixed the problem. In my js function visibilityToggle, the argument id was a html element not a string. i don't know why but it worke
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.