**document.createElement(tag)** creates a new element not yet in the DOM. You must append it to a parent to make it visible. Set properties (textContent, className, id, dataset) before inserting for better performance. Template literals with innerHTML can create complex structures, but watch for XSS.
1Understanding Creating DOM Elements
document.createElement(tag) creates a new element not yet in the DOM. You must append it to a parent to make it visible. Set properties (textContent, className, id, dataset) before inserting for better performance. Template literals with innerHTML can create complex structures, but watch for XSS.
When creating multiple elements with different configurations, document.createElement() is safer. Use innerHTML templates for static, trusted content.
// Build and insert a card
function createCard(title, body) {
const card = document.createElement('div');
card.className = 'card';
card.dataset.testId = 'user-card';
const h3 = document.createElement('h3');
h3.textContent = title; // safe for user data
const p = document.createElement('p');
p.textContent = body;
card.append(h3, p);
return card;
}
document.body.append(createCard('Hello', 'World'));2Practical Example
Here is a real-world application of Creating DOM Elements showing how it is used in production JavaScript code.
// Using innerHTML for trusted templates
function createAlert(type, message) {
const div = document.createElement('div');
// Only trusted content here - no user input!
div.innerHTML = `
<div class="alert alert-${type}">
<strong>${type.toUpperCase()}</strong> ${message}
</div>
`;
return div.firstElementChild;
}3Best Practices
Follow these guidelines when working with Creating DOM Elements:
1. Set all properties before appending to DOM
2. Use createElement for dynamic/user-data content (XSS safe)
3. Use innerHTML for complex static templates
Tip: When creating multiple elements with different configurations, document.createElement() is safer. Use innerHTML templates for static, trusted content.
// Build and insert a card
function createCard(title, body) {
const card = document.createElement('div');
card.className = 'card';
card.dataset.testId = 'user-card';
const h3 = document.createElement('h3');
h3.textContent = title; // safe for user data
const p = document.createElement('p');
p.textContent = body;
card.append(h3, p);
return card;
}
document.body.append(createCard('Hello', 'World'));