1

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

FIDDLE here

+4
source share
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.

http://jsfiddle.net/tQ5ZP/2/

+4
source

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();

Demo

+1
source

Working demo

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:

Working demo

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
source

Source: https://habr.com/ru/post/1537887/


All Articles