Reputation: 118962
I have the following loop:
for(var myScreen in wizardScreens){
if(step==index)$(myScreen).show();
else $(myScreen).hide();
index++;
}
wizardScreens
is defined as $(".wizardScreen", wizard);
, where wizard
is a DOM element. Within the loop, myScreen
is set to a string, instead of being a DOM element. Can anyone explain why that is happening?
Upvotes: 4
Views: 171
Reputation: 28200
In general, the answer is .each
, but that calls a function for every DOM element, which is slower than using jQuery functions which manipulate all nodes in a jQuery object at once, so it's best to avoid it whenever possible. In this case it is definitely possible:
wizardScreens.hide().eq(step).show();
Upvotes: 1
Reputation: 240424
jQuery collections already have a built-in iteration function:
wizardscreens.each(function (index, screen) {
if (index == step)
$(screen).show();
else
$(screen).hide();
}
Or perhaps even better for your use:
var activescreen = wizardscreens.eq(step);
activescreen.show();
wizardscreens.not( activescreen[0] ).hide();
Which avoids explicit iteration altogether.
Upvotes: 3