Select 5 random elements

Here’s how to get 5 random elements from a jQuery selection, no need of plugins!

randomElements = jQuery("li").get().sort(function(){ 
  return Math.round(Math.random())-0.5
}).slice(0,5)

At this point you have 5 DomElements that have been selected randomly from all the LIs that jQuery returned

You can then do whatever you like with them,
e.g change their color:

$(randomElements).css("color","red")

or display their combined text contents:

$(randomElements).text()

Leave a Comment