I am coding a toDo list. When the add button is clicked there is appearing a new li-html-element, but only when I declared "let li = document.createElement("li");" into my "appendListItem" function, otherwise, when I am declaring the variable li as a global variable there will be not appear a new list by clicking the button. Why?
window.onload = function () {
const inp = document.querySelector("input");
//button
const addBtn = document.getElementById("add");
const removeBtn = document.getElementById("remove");
//areas
const p = document.querySelector("p");
const sp = document.querySelector("span");
//Array to save values
let toDo = [];
let index = -1;
//adding content
addBtn.addEventListener(
"click",
(submitEntry = () => {
pushToArray();
appendListItem();
})
);
console.log(index);
pushToArray = () => {
if (inp.value.trim().length !== 0) {
index++;
toDo.push(inp.value);
sp.innerHTML = toDo.length;
inp.value = "";
index + 1;
}
};
appendListItem = () => {
if (index >= 0) {
let li = document.createElement("li");
let content = toDo[index];
let t = document.createTextNode(content);
li.appendChild(t);
document.getElementById("list").appendChild(li);
}
console.log(index);
console.log(toDo[index]);
};
//removing content
removeBtn.addEventListener("click", () => {
inp.value = "";
toDo = [];
sp.innerHTML = toDo.length;
index = -1;
console.clear();
// •removing li, •not only hide
});
document.onkeydown = function () {
if (window.event.keyCode == "13") {
submitEntry();
}
};
};
<body>
<input/>
<button id="add">add</button>
<button id="remove">remove</button>
<span>0</span>
<ul id = "list"></ul>
</body>