Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - shuffle HTML list element order

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?

like image 856
Web_Designer Avatar asked Aug 15 '11 19:08

Web_Designer


1 Answers

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/

like image 128
Alexey Lebedev Avatar answered Sep 22 '22 19:09

Alexey Lebedev