0

How to shuffle labels with same class? here is an example of what I want to do

<div>
A. <label class="shuffle">1</label>
B. <label class="shuffle">2</label>
C. <label class="shuffle">3</label>
</div>

A. 1
B. 2
C. 3

This will be my expected output.

A. 3
B. 1
C. 2

I've been trying THIS solution but it appears that on shuffle it will append at the bottom.

1 Answers1

1

The simplest would be to shuffle an array of text strings and replace text in each

This avoids trying to swap the elements around since you have other text nodes inline with each of them and want those text nodes to stay in place.

var $labels = $('.shuffle'),
  // map text of each to array
  textArr = $labels.map(function(_, el) {
    return $(el).text()
  }).get()
  // random sort text array
  .sort(function() {
    return Math.random() - .5;
  });
  // set new text using matching index in sorted text array
  $labels.text(function(i){
     return textArr[i];
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
A. <label class="shuffle">1</label>
B. <label class="shuffle">2</label>
C. <label class="shuffle">3</label>
</div>
charlietfl
  • 170,828
  • 13
  • 121
  • 150