I have been racking my brain all morning about this. In my HTML code I have a list containing letters a - j and want to console log the letter when it is clicked.
I have created a for loop to run through the nodelist and I can get the script to console log out the number of the element that is being clicked but as soon as I try and get the innerHTML or anything like that it returns undefined.
But when I just type el[3].innerHTML for example into the console it returns the letter I want.
Please help me understand why just because it's going through a for loop does it make it undefined?
I'm not just looking for the solution but also to learn why it's happening so I can become a better coder.
Thanks!
Code:
var list = document.getElementsByTagName('ul')[0];
var el = list.getElementsByTagName('li');
for(var i = 0; i < el.length; i++ ) {
el[i].addEventListener('click', function(f) {
return function(event) {
event.preventDefault();
console.log(f.innerHTML);
}
}(i));
}
f === iandiis an integer, which doesn't have the said property.