How to iterate over siblings using jQuery?
I have the following 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 a loop through a div in the container. I can do this for a loop:
$("#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 an easier way. How can I make it easier? (I don't mind if you don't use the next() function).
jsFiddle: http://jsfiddle.net/S28uC/
I prefer siblings.first() instead of siblings(":nth-child(1)") , but essentially you cannot do without using any option next().length .
Update: If I wrote this from scratch, here's how I do it:
$("#next").click(function() { var $selected = $(".selected").removeClass("selected"); var divs = $selected.parent().children(); divs.eq((divs.index($selected) + 1) % divs.length).addClass("selected"); }); This approach is motivated by two factors:
- When you want to loop through a collection endlessly, a module comes into fashion
- Getting rid of
ifdoes for smart code
When setting divs I preferred $selected.parent().children() over the equivalent of $selected.siblings().add($selected) as a taste - almost endless possibilities.
how about that.
... var selected = $(".selected").removeClass("selected"); if (jQuery(selected).next().addClass("selected").length == 0 {jQuery(selected).siblings().first().addClass("selected");}; ... In the good old AI-style, you are trying to execute an action (addClass), if it worked (length <> 0), you donโt have to do anything else, otherwise you will try again on the first of your brothers and sisters.
You can try this
var cont = $('.container'), i = 0; $("#next").on('click', function() { cont.children().removeClass('selected'); i += 1; if ( i === document.querySelectorAll('.container div').length ) { i = 0; } cont.children().eq(i).addClass('selected'); }); var cont = $('.container'), i = 0; $("#next").on('click', function() { cont.children().removeClass('selected'); // increase index for each click i += 1; // reset i if it reached to last index //(hack to force next to go back to first element when we are at the end) if ( i === document.querySelectorAll('.container div').length ) { i = 0; } cont.children().eq(i).addClass('selected'); }); .selected { background-color: yellow; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <div class="selected">A</div> <div>B</div> <div>C</div> <div>D</div> </div> <button id="next">next!</button> just you increase i for every click, and when it reaches the end ( div length), it will reset.