JAVASCRIPT

Insert DOM Elements Before or After Another Element

Discover how to precisely insert new HTML elements into the DOM relative to an existing element, placing them before or after it using JavaScript methods.

<div id="container">
  <p id="first-paragraph">This is the first paragraph.</p>
  <p id="target-element">This is the target element.</p>
  <p id="last-paragraph">This is the last paragraph.</p>
</div>

<script>
const container = document.getElementById('container');
const targetElement = document.getElementById('target-element');

// Create elements to insert
const newParagraphBefore = document.createElement('p');
newParagraphBefore.textContent = 'I am inserted BEFORE the target.';
newParagraphBefore.style.color = 'red';

const newParagraphAfter = document.createElement('p');
newParagraphAfter.textContent = 'I am inserted AFTER the target.';
newParagraphAfter.style.color = 'green';

// Method 1: Using insertBefore to insert BEFORE a reference element
container.insertBefore(newParagraphBefore, targetElement);

// Method 2: Using insertBefore to insert AFTER a reference element
//    (insert before the next sibling of the reference element)
if (targetElement.nextSibling) {
  container.insertBefore(newParagraphAfter, targetElement.nextSibling);
} else {
  // If targetElement is the last child, append it
  container.appendChild(newParagraphAfter);
}

// Alternative for inserting AFTER (more concise if browser support is not an issue):
// targetElement.after(newParagraphAfter);

console.log('New paragraphs inserted relative to target.');
</script>
How it works: This snippet illustrates how to insert new elements at specific positions within the DOM relative to an existing element. The `parentNode.insertBefore(newNode, referenceNode)` method is used for both 'before' and 'after' insertions. To insert 'before', the `referenceNode` is the element you want to precede. To insert 'after', you pass `referenceNode.nextSibling` as the `referenceNode` to `insertBefore()`. A more modern, concise alternative for inserting after is `element.after(newNode)` if browser compatibility allows.

Need help integrating this into your project?

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

Hire DigitalCodeLabs