javascript - shuffle HTML list element order

Web_Designer picture Web_Designer · Aug 15, 2011 · Viewed 34.5k times · Source

I have a list:

<ul>
    <li>milk</li>
    <li>butter</li>
    <li>eggs</li>
    <li>orange juice</li>
    <li>bananas</li>
</ul>

Using javascript how can I reorder the list items randomly?

Answer

Alexey Lebedev picture Alexey Lebedev · Aug 15, 2012
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/