0

I'm trying to toggle check on a li target but every time I try, I get the error

"Uncaught TypeError: Cannot read property 'addEventListener' of null."

From what I can gather, it might be part of the JavaScript or html but I can't tell. So, what is another way or potential solve to properly adding an eventlistner to the list target.

JavaScript Function

document.getElementById("tasks").addEventListener("click", function(e) {
    if (e.target.nodeName && e.target == "LI") {
        e.target.classList.toggle("checked");
    }
});

HTML Code

<form name="todolist" id="list">    
    <ul id="tasks">
        <li class="checked">                    
            One
        </li>
        <li>
            Two
        </li>
    </ul>   
</form> 
Mamun
  • 58,653
  • 9
  • 33
  • 46
Harsh
  • 44
  • 8

3 Answers3

2

It seems your code is running before the DOM is fully loaded. You can either place your code at the bottom of the body or wrap your code with DOMContentLoaded.

You can try with querySelectorAll() and forEach() like the following way:

.checked{
  color: red;
}
<script>
  document.addEventListener('DOMContentLoaded', (event) => {
    var list = document.querySelectorAll('#tasks li');
    list.forEach(function(el){
      el.addEventListener("click", function(e) {
        this.classList.toggle("checked");
      });
    });
  });
</script>

<form name="todolist" id="list">
  <ul id="tasks">
    <li class="checked">
        One
    </li>
    <li>
        Two
    </li>
  </ul>
</form>
Mamun
  • 58,653
  • 9
  • 33
  • 46
  • Your code works but when I add it to my code, it doesn't. I'm not sure why? Could it be because of how I'm checking the list? I don't get any error either. – Harsh Jun 25 '19 at 15:23
  • @Harsh, is it still the same error? Please try the updated answer:) – Mamun Jun 25 '19 at 15:29
  • Nice, this seemed to work! So basically, I needed to reload the DOM for the checklist to work if I'm understanding this correctly. – Harsh Jun 25 '19 at 15:32
-1

Wrap your code with in window.onload function to make sure element is loaded properly.

window.onload=function(){
document.getElementById("tasks").addEventListener("click", function(e) {
            if (e.target.nodeName && e.target == "LI") {
            e.target.classList.toggle("checked");
        }
});
}
Negi Rox
  • 3,364
  • 1
  • 8
  • 15
-1

You have an issue with the if statement, it should be

//e.target.nodeName == "LI"

<form name="todolist" id="list">

    <ul id="tasks">
        <li class="checked">

            One
        </li>
        <li>
            Two
        </li>
    </ul>


    <script>
    document.getElementById("tasks").addEventListener("click", function(e) {
        console.log(e.target.nodeName)
        if (e.target.nodeName && e.target.nodeName == "LI") {

        e.target.classList.toggle("checked");
    }
});
    </script>
Andrew Daly
  • 507
  • 3
  • 11