I have multiple \'li\' elements:
$(\".my_lis\")
with on the page I want to shuffle them around with JavaScript (I\'m using JQuery). How to do t
It's not too hard actually. The general idea is:
and insert the shuffled nodes--
var items = $('.my_list li').get();
//edit (per comments): avoid confusion
items = shuffle(items);
$('.my_list').empty().append(items);
Where shuffle() can be anything that shuffles the array, I prefer underscore.js but here is a vanilla JavaScript way of doing a shuffle on an Array:
Just an example on shuffling ANY array
function shuffle(items) {
for(var index = 0, ln = items.length; index < ln; index++) {
var item = items[index],
swapIndex = ~~(Math.random() * ln),
swapItem = items[swapIndex];
//Swap places
items.splice(swapIndex, 1, item);
items.splice(index, 1, swapItem);
}
return items;
}