Randomize HTML List: Display HTML List Items Randomly

Learn to randomize HTML list with JavaScript code. The list could either be ordered (OL) or unordered (UL). Method uses rand function to shuffle LI elements.

I had a long list of URLs which I wanted to display on a webpage. Also, I wanted these URLs to always come in a random order. So, I needed a way to grab HTML list and then shuffle all the items in it. Initially, I was a bit at loss but then it turned out to be a very easy thing!

I found a randomizeList() JavaScript function.

The following JavaScript code can randomize an HTML list. The script can handle both Ordered List (OL) and Unordered List (UL) because it works on the LI items which are common to both types of list.

If you want to randomly display items in an HTML list every time the page loads you can calls the randomizeList() function when the onLoad event of the BODY tag occurs. And if you want to give control to the user, for example you want to randomize list on click of a button, then you can call the same function when onClick event of that button occurs.

JavaScript is beautiful!

You would just need to pass the id of the list that you want to randomize. The ID should be defined in the first line of the randomizeList() function given below:

Make sure that you replace the myItems in randomizeList() function with the ID of your HTML list. This method gets hold of all the nodes under the provided list. These nodes are the LI elements. Then it simply uses the rand() function of JavaScript to shuffle these LI elements and sent back a randomly arranged stack. As you can see from this example, being able to traverse Document Object Model (DOM) is essential to develop many web application. Although I am not using createTreeWalker() method here but it is really easy way to traverse DOM tree.

I hope this tip was useful for you. Please let me know if you face any problem in this code. Thank you for using TechWelkin.

Lalit Kumar is the Principal Author and Founder of TechWelkin. He is a web explorer and he enjoys finding useful information on the Internet. He loves to put things together to create a bigger solution. Lalit is passionate about technology, languages and literature. You can contact Lalit via email (techwelkin [at] gmail [dot] com) or Facebook (facebook.com/techwelkin).