I am learning JavaScript programming and while practicing DOM selectors i encountered a problem which is, after selecting the list items, i am adding EventListner to each of the list item, but when i am printing listItem variable inside the EventListner function it prints undefined in console, but when i try to print the listItem variable outside the EventListner function, it prints fine.
i tried to figure out this problem by searching several answers on stack overflow, but i couldn't figure out this problem.
I am trying to get listItem on console instead of undefined.
<!DOCTYPE html>
<html>
<head>
<title>Javascript + DOM</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="box">
<h1>Shopping List</h1>
<p id="first">Get it done today</p>
<input id="userinput" type="text" placeholder="enter items">
<button id="enter">Enter</button>
<ul>
<li>Notebook</li>
<li>Jello</li>
<li>Spinach</li>
<li>Rice</li>
<li>Birthday Cake</li>
<li>Candles</li>
</ul>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
//JavaScript
var input = document.getElementById("userinput");
var enter = document.getElementById("enter");
var ul = document.querySelector("ul");
function addListItemOnClick() {
if (input.value.length > 0) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
input.value = " ";
}
}
function addListItemOnPress() {
if (input.value.length > 0 && event.keyCode === 13) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
input.value = " ";
}
}
enter.addEventListener("click", addListItemOnClick);
input.addEventListener("keypress", addListItemOnPress);
var liItem = document.querySelectorAll("li");
for (var i = 0; i < liItem.length; i++) {
liItem[i].addEventListener("click", function() {
console.log(liItem[i]); // prints undefined
});
// console.log(liItem[i]); //works fine
}
fiddle: https://jsfiddle.net/1yhg9ok4/