JAVASCRIPT

Insert HTML Content at Specific DOM Positions

Discover how to insert raw HTML strings or new elements at precise locations relative to an existing element in the DOM using `insertAdjacentHTML` and `insertAdjacentElement`.

function insertContentRelative(targetElementId, position, content) {
  const targetElement = document.getElementById(targetElementId);
  if (!targetElement) {
    console.error(`Target element with ID '${targetElementId}' not found.`);
    return;
  }

  const validPositions = ['beforebegin', 'afterbegin', 'beforeend', 'afterend'];
  if (!validPositions.includes(position)) {
    console.error(`Invalid position '${position}'. Must be one of: ${validPositions.join(', ')}.`);
    return;
  }

  // Check if content is an HTML string or an actual DOM element
  if (typeof content === 'string') {
    targetElement.insertAdjacentHTML(position, content);
    console.log(`Inserted HTML string at '${position}' relative to #${targetElementId}.`);
  } else if (content instanceof Element) {
    targetElement.insertAdjacentElement(position, content);
    console.log(`Inserted DOM element at '${position}' relative to #${targetElementId}.`);
  } else {
    console.error('Content must be an HTML string or a DOM Element.');
  }
}

// Example Usage:
// HTML structure: <div id="wrapper" style="border: 1px solid black; padding: 10px;">
//                   <p id="target" style="background-color: lightgray;">Target Element</p>
//                 </div>

const targetId = 'target';

// 1. Insert HTML before the target element itself
insertContentRelative(targetId, 'beforebegin', '<p style="color: green;">This is BEFORE the target element (sibling).</p>');

// 2. Insert HTML at the beginning of the target element (first child)
insertContentRelative(targetId, 'afterbegin', '<strong>This is AT THE BEGINNING of target content.</strong>');

// 3. Insert HTML at the end of the target element (last child)
insertContentRelative(targetId, 'beforeend', '<em>This is AT THE END of target content.</em>');

// 4. Insert HTML after the target element itself
insertContentRelative(targetId, 'afterend', '<p style="color: blue;">This is AFTER the target element (sibling).</p>');

// Example with inserting an actual DOM element
const newDiv = document.createElement('div');
newDiv.textContent = 'A new div element.';
newDiv.style.backgroundColor = 'pink';
insertContentRelative('wrapper', 'afterbegin', newDiv);
How it works: This snippet provides a versatile function to insert content (either raw HTML strings or existing DOM elements) at precise locations relative to a specified target element. It utilizes `insertAdjacentHTML` for HTML strings and `insertAdjacentElement` for DOM elements. The `position` argument can be `beforebegin` (before the target), `afterbegin` (inside, at the beginning), `beforeend` (inside, at the end), or `afterend` (after the target). This offers finer control over DOM insertion compared to simpler methods like `appendChild` or `insertBefore`, which only allow adding as children or before a specific child.

Need help integrating this into your project?

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

Hire DigitalCodeLabs