C
C
ChemAli2011-09-02 15:21:33
JavaScript
ChemAli, 2011-09-02 15:21:33

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

4 answer(s)
A
Alexander Keith, 2011-09-02
@ChemAli

Maybe something like this: an example ?

A
Anatoly, 2011-09-02
@taliban

var next = $('span.selected').next();
$('span.selected').removeClass('selected');
next = ( next.length ) ? next : $(firstElem);
next.setClass('selected');

Or have I misunderstood something?

C
ChemAli, 2011-09-02
@ChemAli

Thank you gentlemen! It's time for me to close the work week.
Upvoted both

E
Evgeny Tereshchenko, 2011-09-10
@Jman

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 question

Ask a Question

731 491 924 answers to any question