there is an array of elements with the same classes, it is necessary that every second a class is added / removed to the elements of the array in turn. How to properly describe such a function?

currently stuck on the moment:

var i = 0; setInterval(function(){ var toHover = $('.st-b > a'); var objs = toHover.map(function(){ return this; }).get(); var art = objs[i++]; // art.toggleClass('hover'); console.log(art); console.log('hover+'); setTimeout(function(){ // art.toggleClass('hover'); console.log(art); console.log('hover-'); },1000); if(i >= objs.length) i = 0; },3000); 

if uncomment - an error is displayed

  • it is strange why now the error is not displayed, given that there is an attempt to access the field of a variable that has not yet been initialized var art = objs[i++]; - Grundy
  • apparently crooked scopipastila. var art = objs[i++]; after var objs = toHover.map(function(){ return this; }).get(); coming naturally - wannaBpro
  • You access the variable before it is initialized - br3t
  • The problem is that at this moment objs still undefined , so when you try to objs[i++] will be an exception - Grundy
  • @Grundy corrected the place of the ad art - wannaBpro

1 answer 1

The error is that you are trying to call the jQuery toggleClass method on the native html element. He has no such method, so an exception is thrown.

To fix, you must either use the native DOM tools, classList.toggle or work with jQuery objects.

For example:

 var art = toHover.eq(i); art.toggleClass(...); 

without forgetting to remove the toHover initialization from the interval, if the number of elements will not change during the program operation.


But the main problem is that it looks like you don’t have any elements corresponding to the selector at all, therefore art -> undefined and when you try to call a function, an exception is thrown.

It is worth checking the markup, the selector, the time when the function is called.

  • I thank you for the clarification, the banal $ (art) wrapper helped - wannaBpro
  • @wannaBpro, Actually did not help. art is still undefined and no one knows why, just jQuery on an empty collection does not execute the method called, and you just hid the error. - Grundy
  • @wannaBpro, also pay attention - I removed unnecessary objs . And map(function(){ return this; }) useless for jQuery and if you remove this call, nothing changes - Grundy
  • everything is working! thank you so much! - wannaBpro