JAVASCRIPT
Dynamically Create and Append a List of Elements
Learn to efficiently generate and append multiple DOM elements, such as list items, to a parent container using JavaScript, enhancing dynamic content rendering.
function createAndAppendList(dataArray, parentId) {
const parentElement = document.getElementById(parentId);
if (!parentElement) {
console.error('Parent element not found.');
return;
}
dataArray.forEach(item => {
const listItem = document.createElement('li');
listItem.textContent = item;
parentElement.appendChild(listItem);
});
}
// Example Usage:
// <ul id="myList"></ul>
// const fruits = ['Apple', 'Banana', 'Cherry'];
// createAndAppendList(fruits, 'myList');
How it works: This snippet demonstrates how to programmatically create multiple new DOM elements (list items in this case) from an array of data. It iterates through the array, creates an `<li>` element for each item, sets its text content, and then appends it as a child to a specified parent element, identified by its ID. This is fundamental for rendering dynamic lists or other collections of data.