0
function setclass(element, classname) {
    console.log("event");
    console.log(element);
    element.classList.add(classname);   
    console.log(element.outerHTML);
}

var tpa = document.querySelectorAll("#topnav a");

for(var i=0; i<tpa.length; i++) {
    tpa[i].onclick = () => setclass(tpa[i], "current");
}

I don't understand why the element ins't passed to setclass via setclass(tpa[i],...). console.log(element) logs "undefined" and everything that follows fails because element is undefined.

On the other hand, this works as expected:

var tpa = document.querySelectorAll("#topnav a");
tpa[0].onclick= () => setclass(tpa[0], "current");

2 Answers 2

2
for(var i=0; i<tpa.length; i++) {
  (i=> tpa[i].onclick = () => setclass(tpa[i], "current"))(i);
}

The onclick will happen after your loop has iterated.Therefore tpa[i] will point to the last element. You might bind i trough an IIFE like in the code above, or you use the context:

for(var i=0; i<tpa.length; i++) {
tpa[i].onclick = function(){ setclass(this, "current")};
}
Sign up to request clarification or add additional context in comments.

Comments

1

Bind creates a new function that will have this set to the first parameter passed to bind().

function setclass(element, classname, event) {
    console.log(event);
    console.log(element);
    element.classList.add(classname);   
    console.log(element.outerHTML);
}
var tpa = document.querySelectorAll("#topnav a");
var i,
    len = tpa.length;
for(i=0; i<len; i+=1) {
  tpa[i].onclick = setclass.bind(this, tpa[i], "current");
}
<div id="topnav">
  <a>sfdg</a>
  <a>sfdg</a>
  <a>sfdg</a>
  <a>sfdg</a>
  <a>sfdg</a>
  <a>sfdg</a>
</div>

1 Comment

Yes. However you could prevent overriding the users function trough .bind(this,tpa[i],"current")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.