Search code examples
javascriptcheckboxaddeventlistenercreateelement

Cannot read properties of null (reading 'addEventListener') error


I have such a JavaScript

const checkBox = document.createElement("input")
checkBox.className = "form-check-input me-1 fa-pull-right"
checkBox.type = "checkbox"
li.appendChild(checkBox);
checkBox.id = "checkBox";


checkBox.addEventListener('change', function(e) {
  if (checkBox.checked) {
    li.setAttribute = ("id", "completed");
  } else
    li.removeAttribute = ("id", "completed");
});

code to create an input and when its checked add a style id tag to add line through but i am getting this error.

Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')"


Solution

  • Some of the issues with your code are:

    • The variable li is not defined or declared.
    • setAttribute is a function and not an assignment, it cannot be used with equal signs.
    • A li element is required within the DOM to append.

    I have made the following changes to address the issues in your code:

    • Added the var li declaration.
    • Added a li element within the HTML for appending.
    • Lastly, Equal sign is removed so that when the checkbox is checked, the id completed will be added to the li element.

    const li = document.querySelector("li");
    const checkBox = document.createElement("input")
    checkBox.className = "form-check-input me-1 fa-pull-right"
    checkBox.type = "checkbox"
    checkBox.id = "checkBox";
    li.appendChild(checkBox);
    
    checkBox.addEventListener('change', function() {
      if (checkBox.checked) {
        li.setAttribute("id", "completed");
        console.log(li)
      } else
        li.removeAttribute("id", "completed");
    });
    <li></li>