0

Can someone please tell me how can I grab i properly? By now, it's just displaying the same number (the value of a.length when clicking on any anchor element.

var a = document.getElementsByTagName('a');
  for (i = 0, j = a.length; i< j;i++) {
    a[i].onclick = function() {
      console.log(i); //display a.length in all anchors
      return false;
    }
  }
Verhaeren
  • 1,661
  • 9
  • 10
  • There are a zillion dups of this (I will attempt to find one). `i` has run its course in the `for` loop so it will always be at the ending value because the click handler is called sometime LATER. You have to put `i` in a closure. – jfriend00 Dec 19 '14 at 05:47

1 Answers1

2
var a = document.getElementsByTagName('a');
  for (i = 0, j = a.length; i< j;i++) {
    a[i].idx = i;
    a[i].onclick = function() {
      console.log(this.idx);
      return false;
    }
  }
seung-uk
  • 36
  • 1
  • 2
    Thankyou for showing me how to do it rather than to do what the usual dingbats of this site use to do: marking the question as duplicate, marking the question as off-topic, starting a discussion about how to use the website, etc (you know: little people in charge). Instead of that, you solved my problem, you taught me something, you were useful to me and I'm very grateful. – Verhaeren Dec 19 '14 at 05:53
  • @Verhaeren: Did you read the duplicate, though? That’s what it’s there for. – Ry- Dec 19 '14 at 06:01
  • I did it, and it's marked as duplicated too. Anyway, the fact that there are several similar questions means to me that someone googling for an answer about that particular matter, will have more results to find what he's looking for. Have a great day. – Verhaeren Dec 19 '14 at 06:05