Order by random div elements
from https://stackoverflow.com/questions/59007237/order-by-random-a-list-of-div-elements-with-js
by Lestrae
HTML
<div class="container-category">
<div class="col-3">item 1</div>
<div class="col-3">item 2</div>
<div class="col-3">item 3</div>
<div class="col-3">item 4</div>
<div class="col-3">item ..n</div>
</div>
JavaScript
function shuffle(array) {
var currentIndex = array.length,
temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
// Get the DOM object of the parent div
const container = document.querySelector('.container-category');
// Turn container.children, which is an HTMLCollection, into an array
// See https://stackoverflow.com/a/222847 for more on this
const children = [...container.children];
// The shuffle function above mutates the argument, so here we shuffle
// the array of children; note that this is not yet reflected in the DOM
shuffle(children);
// Reinsert the children to the parent according to the new order
for (const child of children) {
container.appendChild(child);
}