-1

I saw multiple answers to randomize the order of <div> (or <li>s or whatever) using jQuery, but how do I do this using pure javascript?

<ul id="wrapper">
  <li>Answer 1</li>
  <li>Answer 2</li>
  <li>Answer 3</li>
</ul>
iGEL
  • 16,540
  • 11
  • 60
  • 74

2 Answers2

2

Randomly shuffle an array of cloned li elements and replace original with the new ones:

For the shuffleFisherYates function see

function reOrderListItemsRandomly(ulId) {
  const ul = document.querySelector(`ul#${ulId}`);
  const liElems = ul.querySelectorAll(`li`);

  // create new array with cloned li elements and shuffle it
  const nwLiElems = shuffleFisherYates([...liElems]
    .map(li => li.cloneNode(true)));

  // replace the old li with the corresponding li from the 
  // array of new elements, see also
  // https://developer.mozilla.org/en-US/docs/Web/API/Element/replaceWith
  [...liElems].forEach( (li, i) => li.replaceWith(nwLiElems[i]) );

  // see https://stackoverflow.com/a/49555388/58186
  function shuffleFisherYates(array) {
    let i = array.length;
    while (i--) {
      const ri = Math.floor(Math.random() * i);
      [array[i], array[ri]] = [array[ri], array[i]];
    }
    return array;
  }
}

// button handling
document.addEventListener(`click`, handle);

function handle(evt) {
  if (evt.target.id === `shuffle`) {
    return reOrderListItemsRandomly(`wrapper`);
  }
}
<ul id="wrapper">
  <li>Answer 1</li>
  <li>Answer 2</li>
  <li>Answer 3</li>
  <li>Answer 4</li>
  <li>Answer 5</li>
  <li>Answer 6</li>
</ul>
<button id="shuffle">shuffle answers</button>
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • Thanks for pointing out the Fisher-Yates, I've incorporated it into my solution. However, I don't yet see the point of cloning and replacing the `
  • `s.
  • – iGEL Feb 05 '23 at 11:11
  • 1
    Cloning is not really necessary. I would've factored it out later (like you did), if I needed the function. – KooiInc Feb 05 '23 at 22:04