JAVASCRIPT

Dynamically Adding List Items to a Container

Learn to dynamically create and append new HTML elements, like list items, to an existing container using JavaScript DOM manipulation methods.

function addListItem(text, containerId) {
    const container = document.getElementById(containerId);
    if (container) {
        const listItem = document.createElement('li');
        listItem.textContent = text;
        container.appendChild(listItem);
        console.log(`Added: "${text}" to #${containerId}`);
    } else {
        console.error(`Container with ID "${containerId}" not found.`);
    }
}

// Example Usage:
// Assuming you have an <ul id="myList"> in your HTML
// <ul id="myList">
//   <li>Existing Item 1</li>
// </ul>

// Add a new item
addListItem("New Dynamic Item", "myList");
addListItem("Another Item", "myList");

// HTML Structure before adding items:
// <ul id="myList">
//   <li>Existing Item 1</li>
// </ul>

// HTML Structure after adding items:
// <ul id="myList">
//   <li>Existing Item 1</li>
//   <li>New Dynamic Item</li>
//   <li>Another Item</li>
// </ul>
How it works: This snippet demonstrates how to dynamically create a new HTML element (an `<li>`) and append it to an existing container element (a `<ul>`) in the DOM. It uses `document.createElement()` to create the element, sets its text content, and then uses `parentNode.appendChild()` to add it as the last child of the specified container.

Need help integrating this into your project?

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

Hire DigitalCodeLabs