Here is a version that is working, but I'm not sure if it is the best way to do it (this is not the best way, look below)
var $elements = $('.your-selector');
// print it once to see its content
console.log( $elements.get() );
// get all DOM elements in temporary array
var temp = $elements.get();
// randomize that array
temp = temp.sort(function() {
return Math.round( Math.random() ) - 0.5;
});
// iterate the randomized array
// while "$elements" and "temp" have the same length
// each index of "$elements" will be overridden
temp.forEach(function( element, index ) {
// and update the jQuery object
$elements[ index ] = element;
});
// print it again to see the difference
// the order in the original element has been changed
console.log( $elements.get() );
Here is why your versions are not working
var list = $(".content li").sort(Math.round(Math.random())-0.5);
/*
$.fn.sort is not an actual function, or it is... This is not documented ??
Well I don't know what's going on here...
jQuery.fn.sort is not present in the documentation, this it is in the source code
so can we use it ?!
if we can... here is a working version
*/
// jQuery.fn.sort needs a function as parameter
$(".content li").sort(function() {
// and this function needs to return a value
return Math.round(Math.random())-0.5;
});
// THIS is a simplified working example :)
var list = $(".content li").get().sort(function(){
return Math.round(Math.random())-0.5
}).slice(0,$(".content li").length);
/*
First, the slice part seems not useful since you're splicing from 0 to the array length
Then, you use the get method, which return a JavaScript array, and then the sort method
It means that, the result of "sort" will be the sorted array, and not a jQuery object
*/
$(".content li").each(function(i){
$(this).sort(Math.round(Math.random())-0.5)
});
/*
Here, same comment as above: "sort" need a function (with a return value) as parameter
Then, you're using the sort method of a jQuery object containing only one element (this),
so nothing can be sorted
Finally, each only iterate the collection and cannot modify elements order,
or you could do it but it could be harmful
*/
Hope that'll help :)