Reputation: 83
Is there a way to pair elements with the same class without wrapping
<div class="pair1">1</div>
<div class="pair1">2</div>
<div class="pair2">3</div>
<div class="pair2">4</div>
<div class="pair3">5</div>
<div class="pair3">6</div>
then randomly show paired element on page refresh/load so the output would be 1 2 or 3 4 or 5 6
Upvotes: 4
Views: 73
Reputation: 36662
var pairs = ['.pair1','.pair2','.pair3']; // Create an array of strings
var random = Math.floor(Math.random() * pairs.length);
var output = pairs[random]; // choose a string at a random index in your array
$(output).show(); // use random string as selector
Or, if you have an arbitrary number of pairs you could construct your array on the fly with something like this:
var pairs = [];
$('div').each(function() {
var theClass = $(this).attr('class');
pairs.push('.' + theClass);
});
var random = Math.floor(Math.random() * pairs.length);
var output = pairs[random];
$(output).show();
Upvotes: 0
Reputation: 33870
You can use that :
var pairs = $('.pair1, .pair2, .pair3');
var random = Math.floor(Math.random() * pairs.length / 2)+1;
var output = pairs.filter('.pair'+random)
output.show();
Since you have pairs, you'll need to divid the length by 2.
Then, when you have your random number, you get the pair number.
Upvotes: 4
Reputation: 67207
Try,
var pairs = ['.pair1', '.pair2', '.pair3'];
var div = $("div[class^='pair']");
var random = Math.floor(Math.random() * pairs.length);
var output = div.filter(pairs[random]);
output.show();
Upvotes: 1