Here’s an example of how you can shuffle HTML elements using JavaScript:
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
<button onclick="shuffleList()">Shuffle</button>
<script>
function shuffleList() {
const list = document.getElementById("myList");
for (let i = list.children.length; i >= 0; i--) {
list.appendChild(list.children[Math.random() * i | 0]);
}
}
</script>
In the example above, the shuffleList()
function uses JavaScript to access the ul
element with an id
of “myList” and its child elements. The function then randomly rearranges the order of the li
elements by iterating over them in reverse and appending them to the end of the list in a random order. When the “Shuffle” button is clicked, the function is triggered and shuffles the order of the li
elements.
+ There are no comments
Add yours