Switching elements in a list using JQuery

http://stackoverflow.com/questions/23536184/randomize-or-shuffle-ulitems-except-list-items-with-a-specific-class

by 8ogdan

HTML

<ul id="Items">
    <li class="sw">Switchable 1</li>
    <li class="sw">Switchable 2</li>
    <li class="notsw">This should remain 3</li>
    <li class="sw">Switchable 4</li>
    <li class="notsw">This should remain 5</li>
    <li class="sw">Switchable 6</li>
</ul>

<input type="button" class="btn" value="Shuffle" />

JavaScript

//Function that will shuffle only your switchable elements.
function shuffle(nodes, switchableSelector) {
    var length = nodes.length;
    
    //Create the array for the random pick.
    var switchable = nodes.filter("." + switchableSelector);
    var switchIndex = [];
    
    $.each(switchable, function(index, item) {
       switchIndex[index] = $(item).index(); 
    });

    //The array should be used for picking up random elements.
    var switchLength = switchIndex.length;
    var randomPick, randomSwap;
    
    for (var index = length; index > 0; index--) {
        //Get a random index that contains a switchable element.
        randomPick = switchIndex[Math.floor(Math.random() * switchLength)];
        
        //Get the next element that needs to be swapped.
        randomSwap = nodes[index - 1];
        
        //If the element is 'not switchable', ignore and continue;
        if($(randomSwap).hasClass(switchableSelector)) {
            nodes[index - 1] = nodes[randomPick];
            nodes[randomPick] = randomSwap;
        }
    }

    return nodes;
}