0

I want to add new product to the list but I am getting this error. Uncaught TypeError: Cannot read property 'addEventListener' of null at script.js:4

<body>
<ul class="list">
    <li id="text1">test1</li>
    <li id="text2">test2</li>
</ul>
<input type="text" id="data">
<button id="add">add list</button>
var list = document.querySelector("ul");
var product = document.querySelector("#data");
var add = document.querySelector("#add");
add.addEventListener("click", function(){
    var li = document.createElement("li");
    li.textContent=data.value;
    list.appendChild(li);
    data.value="";});

I encounter this error when I want to add a new product to the list.

Photo of the problem

lettoozan
  • 11
  • 3
  • [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) -> [mcve] – Andreas Aug 23 '21 at 12:22
  • The short answer is to move your ` –  Aug 23 '21 at 12:22
  • Yes, when I did as you said, it worked and I didn't get any errors. But why doesn't it work inside Js? – lettoozan Aug 23 '21 at 12:32
  • Read the dupe target and the accepted answer – Andreas Aug 23 '21 at 12:34
  • The script runs before the element exists. If by "inside JS" you mean inline code vs. linking an external script, that has nothing to do with it. A script is (loaded and) executed when the browser encounters the tag, so if the element it tries to reference doesn't exist yet, the error occurs. –  Aug 23 '21 at 14:30

0 Answers0