Problem Statement
What is the correct way to create and add an element to the DOM?
Explanation
The proper way is to create an element with createElement, configure it, then add it to the DOM with appendChild or append.
CreateElement creates a new element node. You then set its properties, attributes, and content. Finally, append it to a parent element to make it visible.
AppendChild is the traditional method that adds one node. Append is newer and can add multiple nodes and text at once.
This approach is safer and more efficient than innerHTML for adding elements. It avoids parsing HTML and potential XSS issues.
You can also use insertBefore, insertAdjacentElement, or replaceChild for different insertion needs.
Understanding element creation is fundamental to dynamic web pages.
Code Solution
SolutionRead Only
// CREATE ELEMENT
const div = document.createElement('div');
console.log(div); // <div></div> (not in DOM yet)
// Set properties
div.id = 'myDiv';
div.className = 'container';
div.textContent = 'Hello World';
// Set attributes
div.setAttribute('data-id', '123');
div.setAttribute('title', 'Tooltip');
// Add styles
div.style.color = 'blue';
div.style.padding = '10px';
// ADD TO DOM with appendChild
document.body.appendChild(div);
// Now visible in page
// CREATE COMPLEX ELEMENT
const card = document.createElement('div');
card.className = 'card';
const title = document.createElement('h3');
title.textContent = 'Card Title';
const text = document.createElement('p');
text.textContent = 'Card description';
const button = document.createElement('button');
button.textContent = 'Click Me';
button.addEventListener('click', () => {
console.log('Button clicked');
});
// Assemble
card.appendChild(title);
card.appendChild(text);
card.appendChild(button);
// Add to page
document.body.appendChild(card);
// APPEND VS APPENDCHILD
const container = document.getElementById('container');
// appendChild - one node only, returns appended node
const p1 = document.createElement('p');
p1.textContent = 'Paragraph 1';
container.appendChild(p1);
// append - multiple nodes and text, returns undefined
const p2 = document.createElement('p');
p2.textContent = 'Paragraph 2';
container.append(p2, 'Some text', document.createElement('span'));
// PREPEND - add at beginning
const first = document.createElement('div');
first.textContent = 'First';
container.prepend(first); // Adds at start
// INSERT AT SPECIFIC POSITION
const reference = document.getElementById('reference');
const newElement = document.createElement('div');
// Insert before reference
reference.parentNode.insertBefore(newElement, reference);
// insertAdjacentElement
reference.insertAdjacentElement('beforebegin', newElement); // Before element
reference.insertAdjacentElement('afterbegin', newElement); // First child
reference.insertAdjacentElement('beforeend', newElement); // Last child
reference.insertAdjacentElement('afterend', newElement); // After element
// REMOVING ELEMENTS
// Modern way
element.remove();
// Old way
parent.removeChild(element);
// REPLACING ELEMENTS
const oldElement = document.getElementById('old');
const newElement2 = document.createElement('div');
newElement2.textContent = 'New';
oldElement.replaceWith(newElement2); // Modern
oldElement.parentNode.replaceChild(newElement2, oldElement); // Old
// CLONING ELEMENTS
const original = document.getElementById('template');
// Shallow clone (no children)
const shallow = original.cloneNode(false);
// Deep clone (with children)
const deep = original.cloneNode(true);
// DOCUMENT FRAGMENT (efficient for multiple elements)
const fragment = document.createDocumentFragment();
for (let i = 0; i < 100; i++) {
const item = document.createElement('li');
item.textContent = `Item ${i}`;
fragment.appendChild(item);
}
// Add all at once (one reflow instead of 100)
document.getElementById('list').appendChild(fragment);
// PRACTICAL EXAMPLE - Create card
function createCard(title, description) {
const card = document.createElement('div');
card.className = 'card';
const heading = document.createElement('h3');
heading.textContent = title;
const para = document.createElement('p');
para.textContent = description;
card.append(heading, para);
return card;
}
const myCard = createCard('Title', 'Description');
document.body.appendChild(myCard);