JAVASCRIPT
Dynamically Create and Append HTML List from Data Array
Learn how to programmatically generate an unordered list (UL) or ordered list (OL) and populate it with items from a JavaScript array, efficiently appending them to the DOM.
function createListFromData(dataArray, parentElementId) {
const parent = document.getElementById(parentElementId);
if (!parent) {
console.error('Parent element not found:', parentElementId);
return;
}
const ul = document.createElement('ul');
ul.className = 'data-list'; // Add a class for styling
dataArray.forEach(item => {
const li = document.createElement('li');
li.textContent = item;
ul.appendChild(li);
});
parent.appendChild(ul);
}
// Example Usage:
const fruits = ['Apple', 'Banana', 'Cherry', 'Date'];
// Assuming there's a div with id="app" in your HTML
// <div id="app"></div>
// createListFromData(fruits, 'app');
How it works: This snippet demonstrates how to dynamically create a `<ul>` element and populate it with `<li>` items based on an array of data. It first gets a reference to the parent container, creates the `<ul>`, iterates through the `dataArray` to create `<li>` elements, sets their `textContent`, appends them to the `<ul>`, and finally appends the complete `<ul>` to the specified parent in the DOM. This is a common pattern for rendering dynamic lists.