diff --git a/theme/assets/javascripts/randomize-element.js b/theme/assets/javascripts/randomize-element.js index c58c8e561d..44b25968c7 100644 --- a/theme/assets/javascripts/randomize-element.js +++ b/theme/assets/javascripts/randomize-element.js @@ -29,7 +29,7 @@ let globalData = document.querySelector("#global-data"); if (globalData.dataset.randomizeElement) { // Get elements to be randomized from meta tag in HTML let randomizeElement = globalData.dataset.randomizeElement; - console.log("Randomizing child elements of " + randomizeElement) + console.log("Randomizing child elements of " + randomizeElement); // Get all elements to be randomized let randomizeChildren = document.querySelectorAll(randomizeElement); @@ -49,14 +49,15 @@ if (globalData.dataset.randomizeElement) { let randomChildren = Array.from(children) .map(value => ({ value, sort: Math.random() })) .sort((a, b) => a.sort - b.sort) - .map(({ value }) => value) + .map(({ value }) => value); - // Clear the contents of the element - children.forEach(e => e.remove()); - - // Iterate over each element of randomChildren - for (const childElement of randomChildren) { - element.appendChild(childElement); + // Replace each element with randomly selected element + for (let i = 0; i < children.length; i++) { + let child = randomChildren[i].cloneNode(true); + child.classList.add("randomized"); + let parent = children[i].parentNode; + parent.insertBefore(child, children[i]); + children[i].remove(); } }