My problem is that - I have this HTML code
<header>
<h1>Javascript Events</h1>
</header>
<main>
<ul id="checklist">
<li>
<span>Apples</span>
<input value="Apples" />
</li>
<li><span>Oranges</span>
<input value="Oranges" />
</li>
<li><span>Bananas</span>
<input value="Bananas" />
</li>
</ul>
</main>
My intention is to add an EventListener to every "li" and "input" element.
I am able to do that with for loop
let checklist = document.getElementById("checklist");
let items = checklist.querySelectorAll("li");
let inputs = checklist.querySelectorAll("input");
for(let i = 0; i<lists.length; i++){
items[i].addEventListener("click", Open)
inputs[i].addEventListener("blur", Change)
inputs[i].addEventListener("keypress", Great)
}
So I decided to try to do the same thing with forEach and that is my idea:
items.forEach(x => {
x.addEventListener("click", EditItem)
})
inputs.forEach((x) =>{
x.addEventListener("blur", updateItem)
x.addEventListener("keypress", itemKeypress);
})
Unfortunately, this code is not working and I think it is because the variable "items" is not an array.
What cause my code to not work and what are potential solutions?
let checklist = document.getElementById("checklist");
let items = checklist.querySelectorAll("li");
let inputs = checklist.querySelectorAll("input");
items.forEach(x => {
x.addEventListener("click", EditItem)
})
inputs.forEach((x) => {
x.addEventListener("blur", updateItem)
x.addEventListener("keypress", itemKeypress);
})
function EditItem(){ console.log('edit'); }
function updateItem(){ console.log('udpate'); }
function itemKeypress(){ console.log('keypress'); }
<header>
<h1>Javascript Events</h1>
</header>
<main>
<ul id="checklist">
<li>
<span>Apples</span>
<input value="Apples" />
</li>
<li><span>Oranges</span>
<input value="Oranges" />
</li>
<li><span>Bananas</span>
<input value="Bananas" />
</li>
</ul>
</main>