Arbitrary display of paired elements
Is there a way to connect elements with the same class without packaging
<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 display the paired item on the refresh / load page so the output will be 1 2 or 3 4 or 5 6
+4
3 answers
You can use this:
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 will need to divide the length by 2.
Then, when you have a random number, you will get the pair number.
+4
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 can build 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();
0