Array to HTML List

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to convert an array into an HTML list using JavaScript. The purpose of this lab is to help you understand how to use Array.prototype.map() and Document.querySelector() to create a list of HTML tags and append them to an existing list in your web page. By the end of this lab, you will have a better understanding of how to manipulate the DOM using JavaScript and create dynamic HTML content.

Converting Array to HTML List

To begin coding, launch the Terminal/SSH and enter node.

This function converts the given array elements into <li> tags and adds them to the list with the given id.

Use Array.prototype.map() and Document.querySelector() to generate a list of HTML tags.

const arrayToHTMLList = (arr, listID) =>
  (document.querySelector(`#${listID}`).innerHTML += arr
    .map((item) => `<li>${item}</li>`)
    .join(""));

Example usage:

arrayToHTMLList(["item 1", "item 2"], "myListID");

Summary

Congratulations! You have completed the Array to HTML List lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like