How to create a new element in JavaScript

Creating new HTML elements dynamically is fundamental for building interactive web applications that generate content based on user actions and data. As the creator of CoreUI with over 25 years of JavaScript experience, I use dynamic element creation extensively for building responsive UI components and data-driven interfaces. The most effective method is using document.createElement() to create elements with proper attributes and content before adding them to the DOM. This approach provides full control over element properties and ensures optimal performance through efficient DOM manipulation.

Use document.createElement() to create new HTML elements and configure their properties before adding them to the DOM.

// Create a new button element
const button = document.createElement('button')
button.textContent = 'Click Me'
button.className = 'btn btn-primary'
button.setAttribute('data-action', 'submit')

// Create a card with multiple child elements
const card = document.createElement('div')
card.className = 'card'

const cardHeader = document.createElement('div')
cardHeader.className = 'card-header'
cardHeader.textContent = 'User Profile'

const cardBody = document.createElement('div')
cardBody.className = 'card-body'
cardBody.innerHTML = '<p>Welcome to your profile!</p>'

// Assemble the card
card.appendChild(cardHeader)
card.appendChild(cardBody)

// Add to the DOM
document.body.appendChild(card)

// Create element with event listener
const deleteButton = document.createElement('button')
deleteButton.textContent = 'Delete'
deleteButton.addEventListener('click', () => {
  console.log('Delete clicked')
})

This example demonstrates creating elements with document.createElement(), setting properties like textContent, className, and custom attributes, then assembling complex structures before DOM insertion. The approach creates the card structure in memory first, then adds it to the DOM in a single operation for better performance. Event listeners can be attached before or after DOM insertion.

Best Practice Note:

This element creation pattern is used extensively in CoreUI’s dynamic components for efficient DOM manipulation. Always set element properties before DOM insertion when possible, use textContent for plain text to prevent XSS vulnerabilities, and consider using DocumentFragment for creating multiple elements efficiently.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author