I am learning Javascript language and so I am on a project while I came across this issue. Here is the code:
function koko() {
items = document.getElementsByTagName("a");
for (var pos = 0; pos < items.length; pos++) {
this.items[pos].addEventListener("click", function() {
console.log(pos);
});
}
}
koko();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<a href="#">Click me 1</a>
<a href="#">Click me 2</a>
<a href="#">Click me 3</a>
</body>
</html>
Every time I click on any item with a
tag I get same value on the console that is items.length
. But I am expecting it to print the position/index of the element that is clicked. For example, if I click Click me 2
it should print 1
. What am I missing here?