Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
38
rated 0 times [  42] [ 4]  / answers: 1 / hits: 23471  / 15 Years ago, thu, november 19, 2009, 12:00:00

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?


More From » jquery

 Answers
10

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()

[#98275] Monday, November 16, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aileenreynap

Total Points: 140
Total Questions: 106
Total Answers: 99

Location: Andorra
Member since Sun, Oct 18, 2020
4 Years ago
;