jquery - Alternately reorder nodeList based on class -
i have nodelist set following:
<div id="container"> <div class="class-a"></div> <div class="class-a"></div> <div class="class-a"></div> <div class="class-b"></div> <div class="class-b"></div> <div class="class-b"></div> </div>
i'm trying reorder div inside #container such output alternating class names:
<div id="container"> <div class="class-a"></div> <div class="class-b"></div> <div class="class-a"></div> <div class="class-b"></div> <div class="class-a"></div> <div class="class-b"></div> </div>
what best approach handle issue? although in example there equal class-a , class-b items, there number or none of either. long there either of 2 alternate.
here's how although there may easier way.
var divs = $("#container > div"); // divs in #container var length = divs.length; // length once , reuse (var = 0; < length; i++) { var currentclass = (i % 2 === 0) ? "class-a" : "class-b"; // class-a evens. class-b odds if (!$(divs[i]).hasclass(currentclass)) { // if not currentclass (var j = + 1; j < length; j++) { // loop through remaining divs if ($(divs[j]).hasclass(currentclass)) { // find next div currentclass // move next element currentclass index j index var element = divs[j]; divs.splice(j, 1); divs.splice(i, 0, element); break; // break inner loop } } } } $("#container").empty().append(divs);
Comments
Post a Comment