# Insert given HTML after an element

Parse an HTML string and insert it after the element.

Canonical: https://1loc.dev/dom/insert-given-html-after-an-element/
Version: 1.0.0
Runtime: JavaScript · modern browsers (DOM)
Verification: Usage lines executed in headless Chromium against the fixture markup; no external services
Updated: 2026-10-28

## Implementation

```javascript
function insertHtmlAfter(html, element) { element.insertAdjacentHTML('afterend', html); }
```

## Usage

Markup:

```html
<p id="intro">Intro</p>
```

Script:

```javascript
insertHtmlAfter('<p>After</p>', document.querySelector('#intro'));
document.querySelector('#intro').nextElementSibling.textContent; // → 'After'
```

Lines marked → were executed in headless Chromium against the markup above, and each result was compared with the value shown. Lines marked e.g. are illustrative.

## Limits

- The string is parsed as HTML: never pass user input, or an attacker can inject markup and event handlers (XSS). For untrusted text, use insertAdjacentText or create elements.
- Unlike innerHTML +=, it does not re-parse the existing content, so listeners and state stay intact.

The function does not validate its arguments. Add checks where it receives untrusted input.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/insert-given-html-after-an-element.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: See original repository history
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
