JAVASCRIPT

Create and Insert New DOM Elements Dynamically

Learn to dynamically create new HTML elements using `document.createElement()` and append them to the DOM with `appendChild()` or `insertBefore()` in JavaScript.

// 1. Create a new div element
const newDiv = document.createElement('div');

// 2. Add some content to the new element
newDiv.textContent = 'This is a dynamically created div!';
newDiv.id = 'myDynamicDiv';
newDiv.style.color = 'blue';

// 3. Append the new element to the body (as the last child)
document.body.appendChild(newDiv);

// 4. Create another element and insert it before a specific existing element
const anotherParagraph = document.createElement('p');
anotherParagraph.textContent = 'This paragraph is inserted before the div.';

const existingElement = document.getElementById('myDynamicDiv');
if (existingElement) {
  document.body.insertBefore(anotherParagraph, existingElement);
}

// Example of creating an element with HTML content
const listItem = document.createElement('li');
listItem.innerHTML = '<strong>Item 1</strong> in a list';

const myList = document.getElementById('myList'); // Assume a <ul id="myList"> exists
if (myList) {
  myList.appendChild(listItem);
}
How it works: This snippet demonstrates how to create new HTML elements from scratch using `document.createElement()`. It then shows two primary methods for inserting these elements into the Document Object Model (DOM): `appendChild()` which adds the element as the last child of a parent, and `insertBefore()` which places an element before a specified reference element. You can also set properties like `textContent`, `id`, and inline styles, or use `innerHTML` for rich content.

Need help integrating this into your project?

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

Hire DigitalCodeLabs