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/
One simple way is this :
You can try this
simply you will increase
i
for each click and when it reach the end (div
s length ) it will be reset.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:
if
makes for smarter-looking codeWhen setting the value of
divs
I preferred$selected.parent().children()
over the equivalent$selected.siblings().add($selected)
as a matter of taste -- there are practically endless possibilities.how about this.
In old good AI manner you try to do the deed (addClass), if it worked (length <> 0) nothing more to do, otherwise you try again on the first of the siblings.