I have the folowing code:
html:
<div class="container">
<div class="selected">A</div>
<div>B</div>
<div>C</div>
<div>D</div>
</div>
<button id="next">next!</button>
jQuery:
$("#next").click(function() {
$(".selected").removeClass("selected").next().addClass("selected");
});
What i want is loop through the divs in the container. I can do this to cycle:
$("#next").click(function() {
if ($(".selected").next().length == 0) {
$(".selected").removeClass("selected").siblings(":nth-child(1)").addClass("selected");
}
else {
$(".selected").removeClass("selected").next().addClass("selected");
}
});
But i think there is a simpler way. How can i make it simpler ? (I don’t mind if you don’t use the next() function).
jsFiddle: http://jsfiddle.net/S28uC/
I ‘d prefer
siblings.first()instead ofsiblings(":nth-child(1)"), but in essence you won’t be able to wrap around without using some variant ofnext().length.Update: If I were writing this from scratch, this is how I ‘d do it:
This approach is motivated by two factors:
ifmakes for smarter-looking codeWhen setting the value of
divsI preferred$selected.parent().children()over the equivalent$selected.siblings().add($selected)as a matter of taste — there are practically endless possibilities.