Someone got a nice code snippet?
+3
A:
How about:
//generate random number with maximum size of the number of p elements
var elems = $('p');
var rand = Math.floor(Math.random() * elems.length);
alert(elems.eq(rand).text());
karim79
2009-08-03 12:41:25
Note this will give you a dom node and not a jquery object. For a jq object use $('p').eq(rand);
redsquare
2009-08-03 12:49:46
@redsquare - you are right, corrected.
karim79
2009-08-03 12:51:10
You might want to change this to only look up the elements once. Also, no need for parseInt. Length is already an integer. Random also is open ended (< 1, not <= 1) so your first version using length itself was correct.
tvanfosson
2009-08-03 13:05:34
@tvanfosson - Thanks. Removed parseInt, and length -1, but I don't get what you said about '...look up the elements once'.
karim79
2009-08-03 13:40:43
I edited your question. I just meant that you could store the results of the $ function in a variable and reuse it instead of running the function each time to get the collection.
tvanfosson
2009-08-03 13:56:28
@tvanfosson - I get you now :)
karim79
2009-08-03 14:09:42