Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save marcomarkkez/53331159aab7521e66df3f5efbae3208 to your computer and use it in GitHub Desktop.
Save marcomarkkez/53331159aab7521e66df3f5efbae3208 to your computer and use it in GitHub Desktop.
Random HTML elements with Vanilla JS
<script>
document.addEventListener("DOMContentLoaded", function(event){
/* Fisher–Yates shuffle algorithm */
var shuffle = function (array) {
var currentIndex = array.length;
var 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;
};
/* Implementation starts here */
let elements = document.querySelectorAll( ".item" );
let wrapper = document.querySelector( ".wrapper" );
/* Copy */
let newElements = Array.from( elements );
/* Remove elements from wrapper */
elements.forEach( (element, index) => {
element.parentNode.removeChild(element);
});
/* Shuffle */
let shuffleNewElements = shuffle(newElements);
/* Console log checking */
console.group("shuffleNewElements:");
shuffleNewElements.forEach( ( element, index ) => {
console.log("Element: "+index);
console.log(element);
});
console.groupEnd();
shuffleNewElements.forEach( (element,index) => {
let clon = element.cloneNode(true);
wrapper.appendChild(clon);
/*
Or
element.parentNode.appendChild(clon);
*/
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment