How to create and update HTML lists (e.g., ul, ol) using JavaScript?

To create and update HTML lists using JavaScript, you can follow these steps:

  1. Create a reference to the parent HTML element where you want to insert the list.
  2. Create an array or retrieve the data you want to display in the list.
  3. Create a loop to iterate through the array or data.
  4. Inside the loop, create a new list item element (
  5. ) and set its content to the current item in the array.
  6. Append the list item to the parent HTML element.
  7. Finally, update the content of the parent HTML element with the newly created list using its innerHTML property.

Here's an example code snippet that demonstrates these steps:

// Step 1: Create a reference to the parent HTML element const listContainer = document.getElementById('list-container'); // Step 2: Define or retrieve data for the list const items = ['Item 1', 'Item 2', 'Item 3']; // Step 3: Loop through the data items.forEach(item => { // Step 4: Create a new list item element const listItem = document.createElement('li'); // Step 4: Set the content of the list item listItem.textContent = item; // Step 5: Append the list item to the parent element listContainer.appendChild(listItem); }); // Step 6: Update the parent HTML element with the list listContainer.innerHTML = '<ul>' + listContainer.innerHTML + '</ul>';

This code creates a new unordered list (

    ) and appends each item in the array as a list item inside the
      . Finally, it updates the content of the parent HTML element (with id='list-container') with the newly created list.