Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select 5 random elements

Tags:

How can I select the first 5 random elements

<ul>     <li>First</li>     <li>Second</li>     <li>Third</li>      ...     <li>N</li> </ul> 

I'm using this plugin:

alert($("li:random").text()); 

but it takes all random elements. I only want the first 5.

Is there another way to do the same thing?

like image 453
AlexC Avatar asked Nov 19 '09 15:11

AlexC


1 Answers

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() 
like image 98
duckyflip Avatar answered Oct 21 '22 20:10

duckyflip