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>
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).