Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I cant find the error in my code which removes elements

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'>&#10004;</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!!!!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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'>&#10004;</span></li>
  <li class="checklistLI" onclick="selectLI(this)">item 2 <span class='liTick d-none'>&#10004;</span></li>
  <li class="checklistLI" onclick="selectLI(this)">item 3 <span class='liTick d-none'>&#10004;</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");
  
}

Demo

checklist

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading