I have been trying to debug the following code for more than 2 hours! I cant seem to figure out what is happening! I will cry now 😭!
var state = 0;
function selectLI(element) {
if (state == 0) {
element.innerHTML = element.innerHTML + "<span class='liTick'>✔</span>";
state = 1;
} else {
var ele = document.getElementsByClassName('checklistLI');
for (var i = 0; i < ele.length; i++) {
var els = ele[i].getElementsByClassName(".liTick");
els.item(0).style.display = "none";
}
}
}
<ul class="checklist">
<li class="checklistLI" onclick="selectLI(this)">item 1</li>
<li class="checklistLI" onclick="selectLI(this)">item 2</li>
</ul>
What the code is supposed to do is that remove the ticks generated by the code above. But it doesn’t work and keep giving me error! If it can’t be debugged then pls provide me with an alternative solution!!!!
>Solution :
As @Andy Holmes suggested in a comment:
This seems a lot more complicated for what it’s actually doing. Why
don’t you just put the ticks there by default, and when clicking on
the relevant li you just toggle a hidden class (which has display:
none;) on the tick rather than this seemingly excessive code?
HTML
<ul class="checklist">
<li class="checklistLI" onclick="selectLI(this)">item 1 <span class='liTick d-none'>✔</span></li>
<li class="checklistLI" onclick="selectLI(this)">item 2 <span class='liTick d-none'>✔</span></li>
<li class="checklistLI" onclick="selectLI(this)">item 3 <span class='liTick d-none'>✔</span></li>
</ul>
CSS
.d-none {
display: none;
}
JS
function selectLI(element) {
const checklistL1 = document.getElementsByClassName('checklist');
document.querySelectorAll('.checklistLI').forEach(function(el) {
el.getElementsByClassName('liTick').item(0).classList.add("d-none");
});
element.getElementsByClassName('liTick').item(0).classList.remove("d-none");
}