How to create a ul and fill it based on a passed array with JavaScript?

Sometimes, we want to create a ul and fill it based on a passed array with JavaScript.

In this article, we’ll look at how to create a ul and fill it based on a passed array with JavaScript.

How to create a ul and fill it based on a passed array with JavaScript?

To create a ul and fill it based on a passed array with JavaScript, we can loop through the array and then add the li elements with the array entry content into the ul element.

For instance, we write

const options = {
  set0: ["Option 1", "Option 2"],
  set1: ["First Option", "Second Option", "Third Option"],
};

const list = "<li>" + options.set0.join("</li><li>") + "</li>";
document.getElementById("list").innerHTML = list;

to get the options.set0 array and then join the entries by calling join with "</li><li>".

And then we wrap the returned string with opening and closing li tags.

Next, we select the ul with getElementById.

And then we set its innerHTML property to list to render the li’s in the ul.

Conclusion

To create a ul and fill it based on a passed array with JavaScript, we can loop through the array and then add the li elements with the array entry content into the ul element.