Answer the question
In order to leave comments, you need to log in
How to loop through elements within Javascript/jQuery?
There is a fixed group of SPAN elements. With some action (say, a click), you need to select one of the elements and make it "current". At the next click, the next SPAN should become “current”. Upon reaching the “end” of this group, the first element should become the current one.
That is, with each click, the “current” element is selected and this happens in a circle.
Only crooked govnokod climbs into my head. Suggest, please, organic, in your opinion, solution.
Thanks in advance.
Answer the question
In order to leave comments, you need to log in
var next = $('span.selected').next();
$('span.selected').removeClass('selected');
next = ( next.length ) ? next : $(firstElem);
next.setClass('selected');
Thank you gentlemen! It's time for me to close the work week.
Upvoted both
The taliban example works if the spans have a common parent.
My option is to iterate over the jQuery object. (choose all elements with the desired class and the setnext function select elements in a circle)
var elements = $('span'),
setnext = function(){
var selected = elements.filter('.selected').removeClass('selected'),
index = elements.index(selected);
index = (++index == elements.length)? 0 : index ;
elements.index(index).setClass('selected')
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question