JAVASCRIPT

Dynamically Create and Append Elements from an Array

Learn how to programmatically create multiple new DOM elements from a JavaScript array of data and efficiently append them to a parent container.

function createAndAppendListItems(dataArray, parentElementId) {
    const parentElement = document.getElementById(parentElementId);
    if (!parentElement) {
        console.error('Parent element not found:', parentElementId);
        return;
    }

    const fragment = document.createDocumentFragment();

    dataArray.forEach(itemText => {
        const listItem = document.createElement('li');
        listItem.textContent = itemText;
        fragment.appendChild(listItem);
    });

    parentElement.appendChild(fragment);
}

// Example Usage:
const myData = ['Apples', 'Bananas', 'Cherries', 'Dates'];
// Assuming an empty <ul> with id="my-list-container" exists in HTML
// <ul id="my-list-container"></ul>
createAndAppendListItems(myData, 'my-list-container');
How it works: This snippet demonstrates how to efficiently create and append multiple new DOM elements. It uses `document.createDocumentFragment()` to minimize reflows and repaints. By appending all new `<li>` elements to the fragment first, and then appending the single fragment to the live DOM, performance is improved compared to appending each `<li>` individually, especially when dealing with many elements.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs