How to prepend an element in JavaScript
Prepending elements to the DOM allows you to add content at the beginning of a container, essential for dynamic lists, notifications, and priority content placement.
As the creator of CoreUI with over 25 years of JavaScript experience, I use element prepending for building dynamic lists, notifications, and priority content areas.
The most reliable method is using insertBefore() to insert an element before the first child, or the modern prepend() method for direct prepending.
This provides precise control over element positioning and maintains proper DOM structure for complex dynamic interfaces.
Use prepend() method or insertBefore() to add elements at the beginning of a parent container in the DOM.
// Modern prepend method
const container = document.getElementById('container')
const newElement = document.createElement('div')
newElement.textContent = 'This appears first'
newElement.className = 'priority-content'
container.prepend(newElement)
// Traditional insertBefore method
const firstChild = container.firstChild
const anotherElement = document.createElement('p')
anotherElement.textContent = 'Inserted before first child'
container.insertBefore(anotherElement, firstChild)
// Prepend multiple elements
const list = document.getElementById('todoList')
list.prepend(
document.createElement('li'),
'High priority: ',
document.createTextNode('Urgent task')
)
// Prepend with fragment for multiple elements
const fragment = document.createDocumentFragment()
for (let i = 3; i >= 1; i--) {
const item = document.createElement('div')
item.textContent = `Priority item ${i}`
fragment.appendChild(item)
}
container.prepend(fragment)
// Prepend notification example
function showNotification(message) {
const notification = document.createElement('div')
notification.className = 'notification'
notification.textContent = message
document.body.prepend(notification)
// Auto remove after 3 seconds
setTimeout(() => notification.remove(), 3000)
}
The prepend() method adds elements at the beginning of the parent, while insertBefore() inserts before a specific child node. The prepend() method can accept multiple arguments including text strings and elements. Using DocumentFragment with prepend allows efficient batch insertion of multiple elements while maintaining proper order.
Best Practice Note:
This prepending pattern is used in CoreUI’s notification and dynamic list components for priority content placement. Always consider the visual and logical impact of prepending elements, especially in user interfaces where content order affects user experience.



