I am trying to do a simple slider, but I have I this problem:
Uncaught TypeError: Cannot read property 'classList' of undefined
This is my code:
var div = document.querySelectorAll("div");
for(var i = 0; i < 6; i++){
div[i].onclick = function() {
this.classList.remove("active");
div[i+1].classList.add("active");
}
}
Can any one help me please ?
I am trying to do a simple slider, but I have I this problem:
Uncaught TypeError: Cannot read property 'classList' of undefined
This is my code:
var div = document.querySelectorAll("div");
for(var i = 0; i < 6; i++){
div[i].onclick = function() {
this.classList.remove("active");
div[i+1].classList.add("active");
}
}
Can any one help me please ?
Share Improve this question edited Mar 21, 2017 at 14:37 hungerstar 21.7k6 gold badges51 silver badges62 bronze badges asked Mar 21, 2017 at 14:32 user7148537user7148537 2-
When you get to the last element
i+1
is out of bounds. – tmslnz Commented Mar 21, 2017 at 14:49 - @tmslnz: Answers do not go in the ments section, thanks – Lightness Races in Orbit Commented Mar 21, 2017 at 14:57
1 Answer
Reset to default 2It seems like this might occur because i is scoped to the outer function, so it'll always be set to the max value for i. Because of this, div[i + 1]
will always be undefined. What you could do is:
div[i].onclick = function(idx) {
this.classList.remove("active");
if(idx < div.length - 1) div[idx + 1].classList.add("active");
}.bind(div[i], i);
What bind does is it takes a snapshot of the values of variables that you are passing to functions, as well as a value for "this". The value for "this" es first, then arguments for the function follow it. It then returns the function it was called on, with some subset of its arguments bound to the values you provided. Any arguments that were not bound can be provided by the caller, but all bound arguments must e before arguments supplied by the caller.