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/

4
  • 1
    this doesnt return a ur. it returns the element. use console.log instead of alert. If you want to use i use a closure since your i has expired (value = links.length) by the time callback is invoked. Just do this.getAttribute("href") Commented Dec 18, 2013 at 3:07
  • the toString() of <A> tags is the url in some browsers. your for loop has no scope. Commented Dec 18, 2013 at 3:07
  • 1
    The way you attach events to elements using for will give you errors. Don't do that. Commented Dec 18, 2013 at 3:12
  • 1
    As someone else mentioned, this is a common trouble that stems from how JavaScript scopes closure variables. This tweak to your JSFiddle is one way that you could isolate i so that it will be what you expect when the event handler is triggered later: jsfiddle.net/2DRrJ/1 Commented Dec 18, 2013 at 3:17

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@hicurin - The last i will be equal to links.length because of i++.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.