How to get random element in jquery?
You can write a custom filter (taken from here):
jQuery.jQueryRandom = 0;
jQuery.extend(jQuery.expr[":"], {
random: function(a, i, m, r) {
if (i == 0) {
jQuery.jQueryRandom = Math.floor(Math.random() * r.length);
};
return i == jQuery.jQueryRandom;
}
});
Example usage:
$('.class:random').click()
The same thing but as a plugin instead:
jQuery.fn.random = function() {
var randomIndex = Math.floor(Math.random() * this.length);
return jQuery(this[randomIndex]);
};
Example usage:
$('.class').random().click()
var n_elements = $(".someClass").length;
var random = Math.floor(Math.random()*n_elements);
$(".someClass").eq(random).click();
If you don't want to hard code the number of elements to choose from, this works:
things = $('.class');
$(things[Math.floor(Math.random()*things.length)]).click()