0

I am not using libraries like Jquery. This is what i have:

HTML:

<a href="#aid" class="nav-link"> A link </a>
<a href="#anotherid" class="nav-link"> Another link </a>
<a href="#oneidmore" class="nav-link"> One more link </a>

Javascript:

var links = document.getElementsByClassName("nav-link");
for(var i = 0; i < links.length; i++) {
    links[i].onclick = function(){
        alert(this); // Returns a url
        alert(links[i]); // Returns "undefined"
    };
};

What i am looking for, is get the respective element that i am clicking. And then, get the href attributte (just the ID that contains), etc.

What i am doing wrong?

PS: Sorry if the title is poor

EDIT:

I made a JSfiddle: http://jsfiddle.net/2DRrJ/

yukatta
  • 505
  • 2
  • 7
  • 16

1 Answers1

3

this is the <a> element as you expected, the URL is its .toString() value.

As for the undefined link[i], it's because the i variable is equal to links.length at the end of the loop's execution and links[links.length] is indeed undefined. This is a result of how scoping (and hoisting) works in JavaScript.

dee-see
  • 23,668
  • 5
  • 58
  • 91