javascript - shuffle HTML list element order

Solution 1:

var ul = document.querySelector('ul');
for (var i = ul.children.length; i >= 0; i--) {
    ul.appendChild(ul.children[Math.random() * i | 0]);
}

This is based on Fisher–Yates shuffle, and exploits the fact that when you append a node, it's moved from its old place.

Performance is within 10% of shuffling a detached copy even on huge lists (100 000 elements).

http://jsfiddle.net/qEM8B/

Solution 2:

Simply put, like this:

JS:

var list = document.getElementById("something"),
button = document.getElementById("shuffle");
function shuffle(items)
{
    var cached = items.slice(0), temp, i = cached.length, rand;
    while(--i)
    {
        rand = Math.floor(i * Math.random());
        temp = cached[rand];
        cached[rand] = cached[i];
        cached[i] = temp;
    }
    return cached;
}
function shuffleNodes()
{
    var nodes = list.children, i = 0;
    nodes = Array.prototype.slice.call(nodes);
    nodes = shuffle(nodes);
    while(i < nodes.length)
    {
        list.appendChild(nodes[i]);
        ++i;
    }
}
button.onclick = shuffleNodes;

HTML:

<ul id="something">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>
<button id="shuffle" type="button">Shuffle List Items</button>

Demo: http://jsbin.com/itesir/edit#preview

Solution 3:

    var list = document.getElementById("something");
    function shuffleNodes() {
        var nodes = list.children, i = 0;
        nodes = Array.prototype.sort.call(nodes);
        while(i < nodes.length) {
           list.appendChild(nodes[i]);
           ++i;
        }
    }
    shuffleNodes();

Solution 4:

Use this:

function htmlShuffle(elem) {
    function shuffle(arr) {
        var len = arr.length;
        var d = len;
        var array = [];
        var k, i;
        for (i = 0; i < d; i++) {
            k = Math.floor(Math.random() * len);
            array.push(arr[k]);
            arr.splice(k, 1);
            len = arr.length;
        }
        for (i = 0; i < d; i++) {
            arr[i] = array[i];
        }
        return arr;
    }
    var el = document.querySelectorAll(elem + " *");
    document.querySelector(elem).innerHTML = "";
    
    let pos = [];
    for (let i = 0; i < el.length; i++) {
        pos.push(i);
    }
    
    pos = shuffle(pos);
    for (let i = 0; i < pos.length; i++) {
        document.querySelector(elem).appendChild(el[pos[i]]);
    }
}

htmlShuffle("ul");
<ul>
    <li>milk</li>
    <li>butter</li>
    <li>eggs</li>
    <li>orange juice</li>
    <li>bananas</li>
</ul>