JAVASCRIPT
Dynamically Generate and Append a List of Elements
Learn how to dynamically create multiple HTML elements (like list items) and append them to an existing parent container using JavaScript.
// HTML Structure:
// <ul id="dynamicList"></ul>
// <button id="addItemsBtn">Add 5 Items</button>
document.addEventListener('DOMContentLoaded', () => {
const dynamicList = document.getElementById('dynamicList');
const addItemsBtn = document.getElementById('addItemsBtn');
let currentItemCount = 0;
addItemsBtn.addEventListener('click', () => {
for (let i = 0; i < 5; i++) {
currentItemCount++;
const listItem = document.createElement('li'); // Create a new <li> element
listItem.textContent = `Dynamic Item ${currentItemCount}`; // Set its text content
listItem.setAttribute('data-item-id', currentItemCount); // Add a data attribute for example
dynamicList.appendChild(listItem); // Append the new <li> to the <ul>
}
console.log(`${currentItemCount} items now in the list.`);
});
});
How it works: This code snippet illustrates how to dynamically create and append multiple HTML elements to the DOM. It creates a button that, when clicked, generates five new list items (`<li>`) with unique text content and a `data-item-id` attribute. Each newly created `<li>` is then appended to an existing unordered list (`<ul>`) on the webpage. This is a fundamental task for rendering dynamic content fetched from APIs or generated client-side.