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>
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>
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>
Here my solution:
<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>
<script>
(function() {
const wrapper = document.getElementById("wrapper")
const children = Array.from(wrapper.children)
for(i = children.length - 1; i > 0; i--) {
const ri = Math.floor(Math.random() * (i + 1));
[children[ri], children[i]] = [children[i], children[ri]]
}
children.forEach(node => wrapper.appendChild(node))
})()
</script>
First it takes the children of the wrapper and converts them to an Array using Array.from
. Then it's using Fisher-Yates shuffle algorithm to shuffle the array and finally we call forEach
on the array and add each <li>
again to the wrapper in order of the shuffled array (adding an element will remove it from it's previous position).