How to append an element in JavaScript
Appending elements to the DOM is fundamental for creating dynamic content and building interactive web applications that respond to user actions.
With over 25 years of JavaScript development experience and as the creator of CoreUI, I use element appending extensively for building dynamic UI components.
The most effective method is using the appendChild() method which adds an element as the last child of a parent element.
This provides reliable element insertion with proper DOM structure maintenance and event handling capabilities.
Use appendChild() method to add elements as the last child of a parent element in the DOM structure.
// Create and append a new element
const container = document.getElementById('container')
const newDiv = document.createElement('div')
newDiv.textContent = 'New content'
newDiv.className = 'dynamic-content'
// Append the element
container.appendChild(newDiv)
// Append multiple elements
const fragment = document.createDocumentFragment()
for (let i = 0; i < 3; i++) {
const item = document.createElement('li')
item.textContent = `Item ${i + 1}`
fragment.appendChild(item)
}
document.getElementById('list').appendChild(fragment)
// Modern append method (supports multiple nodes and strings)
const header = document.querySelector('header')
header.append(
document.createElement('nav'),
' - ',
'Navigation added'
)
// Append with event listener
const button = document.createElement('button')
button.textContent = 'Click me'
button.addEventListener('click', () => alert('Clicked!'))
container.appendChild(button)
The appendChild() method adds the specified element as the last child of the target parent. For multiple elements, use DocumentFragment to batch DOM operations efficiently. The modern append() method can accept multiple arguments including text strings and multiple elements. Always create elements with proper attributes and event listeners before appending to ensure complete functionality.
Best Practice Note:
This element appending pattern is used throughout CoreUI components for dynamic content generation. Use DocumentFragment when appending multiple elements to minimize DOM reflows, and always set element properties before appending for optimal performance.



