JAVASCRIPT

Dynamically Create and Append Elements to the DOM

Learn how to programmatically create new HTML elements, set their attributes and content, and efficiently append them to a parent element in the DOM using JavaScript.

function createAndAppendListItem(parentId, items) {
  const parentElement = document.getElementById(parentId);
  if (!parentElement) {
    console.error(`Parent element with ID '${parentId}' not found.`);
    return;
  }

  items.forEach((itemText, index) => {
    const listItem = document.createElement('li');
    listItem.textContent = itemText;
    listItem.setAttribute('data-index', index);
    listItem.classList.add('dynamic-item');
    parentElement.appendChild(listItem);
  });
}

// Example Usage:
// Assuming you have a <ul id="myList"></ul> in your HTML
// createAndAppendListItem('myList', ['Item A', 'Item B', 'Item C']);
How it works: This snippet defines a function `createAndAppendListItem` that takes a parent element's ID and an array of strings. For each string, it creates a new `<li>` element using `document.createElement()`, sets its text content, adds a `data-index` attribute, and a CSS class. Finally, it appends the newly created element to the specified parent using `parentElement.appendChild()`. This is a common pattern for rendering dynamic content.

Need help integrating this into your project?

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

Hire DigitalCodeLabs