views:

182

answers:

1

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
Note this will give you a dom node and not a jquery object. For a jq object use $('p').eq(rand);
redsquare
@redsquare - you are right, corrected.
karim79
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
@tvanfosson - Thanks. Removed parseInt, and length -1, but I don't get what you said about '...look up the elements once'.
karim79
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
@tvanfosson - I get you now :)
karim79