JAVASCRIPT

Dynamically Create, Append, and Prepend DOM Elements

Learn to programmatically create new HTML elements, set their content and attributes, then efficiently append them to the end or prepend them to the beginning of a parent container.

// Create a new div element
const newDiv = document.createElement('div');
newDiv.textContent = 'I am a new element!';
newDiv.className = 'dynamic-item';
newDiv.setAttribute('data-id', '123');

// Get a parent element by its ID
const parentContainer = document.getElementById('app');

// Append the new div as the last child
if (parentContainer) {
    parentContainer.appendChild(newDiv);
}

// Create another element for prepending
const headerElement = document.createElement('h2');
headerElement.textContent = 'Prepended Header';
headerElement.style.color = 'blue';

// Prepend the header element as the first child
if (parentContainer && parentContainer.firstChild) {
    parentContainer.insertBefore(headerElement, parentContainer.firstChild);
} else if (parentContainer) {
    // If no first child, just append (it will be the first)
    parentContainer.appendChild(headerElement);
}

/*
Example HTML:
<div id="app">
    <p>Existing content</p>
</div>
Result:
<div id="app">
    <h2>Prepended Header</h2>
    <p>Existing content</p>
    <div class="dynamic-item" data-id="123">I am a new element!</div>
</div>
*/
How it works: This snippet demonstrates how to create new HTML elements from scratch using `document.createElement()`. It then shows how to set their `textContent`, add CSS classes with `className`, and custom data attributes using `setAttribute()`. Finally, it illustrates two common methods for adding these new elements to the DOM: `appendChild()` to add them as the last child of a parent, and `insertBefore()` to prepend them as the first child or before a specific existing child.

Need help integrating this into your project?

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

Hire DigitalCodeLabs