← Back to all snippets
JAVASCRIPT

Insert a New Element Before an Existing One

Master the `insertBefore()` method to precisely position new HTML elements within the DOM, allowing you to insert content before a specified reference element.

const parentElement = document.getElementById('container');
const referenceElement = document.getElementById('secondItem');

const newParagraph = document.createElement('p');
newParagraph.textContent = 'This is a new paragraph, inserted before the second item.';
newParagraph.classList.add('inserted-item');

if (parentElement && referenceElement) {
  parentElement.insertBefore(newParagraph, referenceElement);
}
How it works: This code creates a new paragraph element and then uses the `insertBefore()` method to place it as a child within `parentElement`, specifically right before the `referenceElement`. This provides fine-grained control over the precise positioning of new elements within the DOM.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs