JAVASCRIPT

Dynamically Create and Append Multiple DOM Elements

Learn to efficiently create new HTML elements, set their content and attributes, and append them to an existing DOM element using JavaScript for dynamic page updates.

const listContainer = document.getElementById('myList');

const itemsToAdd = [
  { text: 'First item', className: 'list-item-odd' },
  { text: 'Second item', className: 'list-item-even' },
  { text: 'Third item', className: 'list-item-odd' }
];

itemsToAdd.forEach(itemData => {
  const listItem = document.createElement('li');
  listItem.textContent = itemData.text;
  listItem.className = itemData.className;
  listItem.setAttribute('data-id', `item-${listContainer.children.length + 1}`);
  listContainer.appendChild(listItem);
});

// HTML structure might look like:
// <ul id="myList"></ul>
How it works: This snippet demonstrates how to dynamically create multiple new 'li' elements, assign them text content, CSS classes, and custom data attributes, then append each to an existing 'ul' element with the ID 'myList'. It's useful for populating lists, menus, or any section of your page with data fetched asynchronously or generated on the fly. The `document.createElement()` method creates the element, properties like `textContent` and `className` set its content and style, `setAttribute()` handles custom attributes, and `appendChild()` places it into the DOM.

Need help integrating this into your project?

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

Hire DigitalCodeLabs