views:

882

answers:

4

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.

Or is there another way to do the same thing?

Thanks !

+1  A: 
$("li:lt(5):random").text()
Nikolas Stephan
But it takes always the first 5 (
Alexander Corotchi
+1  A: 

Get a random number index, 1-5, and get the child of the ul with that index. Like so:

var index = Math.ceil(Math.random()*5);  //nth-child indexes start at 1
alert($("ul:nth-child(" + index + ")").text());
Frank DeRosa
Oh, this is completely wrong. I read the question as requesting one random element out of the first five, not five random elements from the set. I think I need sleep! :D
Frank DeRosa
Got here by searching exactly for this kind of solution. So answering to misread qestions is not always bad :)
Zlatev
+7  A: 

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()
duckyflip
+1, though I'm curious as to why you spelt "random" consistently correctly in the text, and consistently incorrectly in the code snippets... :-)
Andrzej Doyle
The general idea is good, but you shouldn't shuffle an array like that. Sorting is an inefficient way to shuffle an array, and an inconsistent comparison can cause problems (even potentially causing the sort to loop indefinitely). It's better to use a Fisher-Yates shuffle (http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle).
Matthew Crumley
That won't get you a randomly sorted array. Here's an article about it (it's Objective-C, but shouldn't matter) http://cocoawithlove.com/2010/06/sorting-nsmutablearray-with-random.html
Georg
A: 

Why not just do this, it seems pretty efficient:

jQuery('li:random').slice(0, 5)

Gregory Magarshak