jQuery Insert Content After an Element
This guide explains how to insert content immediately after a specified HTML element using jQuery. You will learn the exact method designed for this purpose, its proper syntax, practical code examples, and an alternative method that achieves the same result using a different structure.
The .after() Method
The primary jQuery method to insert content immediately after an
element is .after(). It inserts the specified content as a
sibling directly following the matched element in the DOM tree.
Syntax
$(selector).after(content1 [, content2, ...]);- selector: The target element after which the new content will be placed.
- content: The HTML string, DOM element, text node, or jQuery object you want to insert. You can pass multiple arguments to insert multiple items at once.
Basic Example
Suppose you have the following HTML markup:
<div class="target-box">Existing Box</div>To insert a new paragraph immediately after this div,
run the following jQuery code:
$('.target-box').after('<p>This content was inserted immediately after.</p>');The resulting HTML structure will be:
<div class="target-box">Existing Box</div>
<p>This content was inserted immediately after.</p>Inserting Multiple Elements or DOM Objects
The .after() method accepts existing DOM elements or
multiple elements simultaneously:
const newElement = document.createElement('span');
newElement.textContent = ' (Verified)';
$('h1').after(newElement, '<em>Note: Updated today</em>');Alternative Method:
.insertAfter()
jQuery also provides the .insertAfter() method. It
performs the exact same DOM operation as .after(), but
reverses the syntax order by placing the content to be inserted before
the target selector.
Syntax
$(content).insertAfter(target);Example
$('<p>This content was inserted immediately after.</p>').insertAfter('.target-box');Use .after() when your logic starts with the existing
target element, and use .insertAfter() when you have
created new content and want to position it relative to an existing
element.