← Back to all snippets
JAVASCRIPT

Insert Elements Before or After Others

Master precise DOM element insertion using insertBefore and insertAdjacentElement to place new elements relative to existing ones, controlling their position.

const newElement = document.createElement('h3');
newElement.textContent = 'Newly inserted heading!';

const referenceElement = document.getElementById('section-content');

if (referenceElement) {
  // 1. Insert 'newElement' directly before 'referenceElement'
  // Requires the parent node of the reference element
  referenceElement.parentNode.insertBefore(newElement, referenceElement);
  console.log('Heading inserted before reference element.');

  // 2. Using insertAdjacentElement for more flexible positioning
  const anotherNewElement = document.createElement('small');
  anotherNewElement.textContent = '(Added after)';

  // 'afterend': Inserts after the target element itself
  referenceElement.insertAdjacentElement('afterend', anotherNewElement);
  console.log('Small text inserted after reference element.');

  // Other insertAdjacentElement positions:
  // 'beforebegin': Before the element itself.
  // 'afterbegin': Just inside the element, before its first child.
  // 'beforeend': Just inside the element, after its last child.
} else {
  console.error('Reference element not found.');
}
How it works: This snippet explores methods for inserting new elements precisely relative to existing ones. `insertBefore()` inserts a new element directly before a specified reference element. It requires knowing the parent of the reference element. `insertAdjacentElement()` offers more flexibility with four positions: `beforebegin` (before the element itself), `afterbegin` (inside, as first child), `beforeend` (inside, as last child), and `afterend` (after the element itself). These methods allow fine-grained control over DOM structure.

Need help integrating this into your project?

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

Hire DigitalCodeLabs