JAVASCRIPT

Insert Elements Before or After a Specific Node

Learn to precisely position new DOM elements by inserting them immediately before or after an existing reference element using JavaScript's powerful 'insertAdjacentElement' method.

function insertElementAround(referenceElementId, newElementTagName, newElementText, position) {
  const referenceElement = document.getElementById(referenceElementId);
  if (!referenceElement) {
    console.error(`Reference element with ID '${referenceElementId}' not found.`);
    return;
  }

  const newElement = document.createElement(newElementTagName);
  newElement.textContent = newElementText;
  newElement.style.border = '1px solid blue';
  newElement.style.padding = '5px';
  newElement.style.margin = '5px 0';

  // Positions:
  // 'beforebegin': Before the element itself.
  // 'afterbegin': Just inside the element, before its first child.
  // 'beforeend': Just inside the element, after its last child.
  // 'afterend': After the element itself.
  const validPositions = ['beforebegin', 'afterbegin', 'beforeend', 'afterend'];
  if (!validPositions.includes(position)) {
    console.error(`Invalid position '${position}'. Must be one of: ${validPositions.join(', ')}`);
    return;
  }

  referenceElement.insertAdjacentElement(position, newElement);
  console.log(`Inserted new element '${newElementText}' ${position} '${referenceElementId}'.`);
  return newElement;
}

// Usage example:
// HTML: <div id="mainContent"><p id="refParagraph">This is the reference paragraph.</p></div>
// insertElementAround('refParagraph', 'div', 'Content BEFORE reference', 'beforebegin');
// insertElementAround('refParagraph', 'span', 'Content AFTER reference', 'afterend');
// insertElementAround('mainContent', 'h2', 'Title inside at start', 'afterbegin');
// insertElementAround('mainContent', 'footer', 'Footer inside at end', 'beforeend');
How it works: This snippet utilizes the `insertAdjacentElement()` method, a versatile tool for inserting new elements relative to an existing reference element. Unlike `appendChild()`, which only adds to the end of a parent, `insertAdjacentElement()` offers precise control over placement: `beforebegin` (as a sibling before), `afterbegin` (as the first child), `beforeend` (as the last child), or `afterend` (as a sibling after). This is invaluable for maintaining specific document structure when dynamically updating content.

Need help integrating this into your project?

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

Hire DigitalCodeLabs