The .replaceWith() method removes matched elements and inserts new content in one step — target first, replacement second. This tutorial covers HTML string replacements, moving existing DOM nodes, the callback form since jQuery 1.4, comparisons with .replaceAll() and .html(), what the return value refers to, and five practical try-it examples from the official jQuery API.
01
Target first
Direct
02
Swap nodes
Full replace
03
Callback
Since 1.4
04
vs replaceAll
Pair API
05
Returns old
Removed set
06
Since 1.2
Core API
Fundamentals
Introduction
When you already know which elements to remove — every <p>, a clicked button, or a stale widget container — .replaceWith() is the natural choice. You select the old nodes, pass the new content, and jQuery swaps them in a single call.
Available since jQuery 1.2, .replaceWith( newContent ) accepts an HTML string, DOM element, array of elements, or jQuery object as replacement. Since jQuery 1.4, pass a callback function that returns the new content for each matched element individually.
Pair with .replaceAll() when replacement content is selected first. Browse the jQuery DOM hub for related manipulation methods.
Concept
Understanding the .replaceWith() Method
.replaceWith( newContent ) operates on the jQuery collection you want to remove. Each matched element is deleted from the DOM and newContent is inserted in its place. The method returns the original jQuery object — the removed elements — not the replacement.
Replaced nodes lose all jQuery data and event handlers. When newContent is an existing DOM node already on the page, jQuery moves it into position rather than cloning it (for single-target swaps).
💡
Beginner Tip
The official jQuery demo runs $( "p" ).replaceWith( "<b>Paragraph.</b>" ). Every paragraph is removed and a bold element takes its place. Same outcome as $( "<b>Paragraph.</b>" ).replaceAll( "p" ) — opposite syntax.
Foundation
📝 Syntax
jQuery .replaceWith() supports two forms:
Replace with content — since 1.2
jQuery
.replaceWith( newContent )
newContent — HTML string, DOM element, array of elements, or jQuery object.
Returns — the original jQuery collection of removed elements.
Replace with callback — since 1.4
jQuery
.replaceWith( function )
$( "button" ).replaceWith( function() {
return $( "<div>" + $( this ).text() + "</div>" );
} );
Official replaceWith pattern
jQuery
$( "p" ).replaceWith( "<b>Paragraph.</b>" );
Cheat Sheet
⚡ Quick Reference
Goal
Code
Replace with HTML string
$("p").replaceWith("<strong>New</strong>")
Replace clicked element
$(this).replaceWith("<div>…</div>")
Replace with existing node
$(".old").replaceWith($("#new"))
Dynamic replacement
$("p").replaceWith(function(){ … })
Content-first alternative
$(content).replaceAll("p")
Replace inner HTML only
$("#box").html(content)
Compare
📋 .replaceWith() vs .replaceAll() vs .html() vs .remove()
Four DOM change APIs — know what each one replaces and returns.
.replaceWith()
target first
Remove matched elements, insert newContent — returns removed jQuery set
.replaceAll()
content first
Replacement collection replaces targets — reversed syntax, returns replacement set
.html()
inner only
Replace children inside the element — outer tag remains in the DOM
.remove()
delete
Remove matched elements with no replacement — also returns removed set
Hands-On
Examples Gallery
Examples 1–2 follow the official jQuery API documentation. Examples 3–5 cover moving existing nodes, callback replacements, and unwrapping a container. Use DevTools or the Try-it links to run each snippet in the browser.
📚 Getting Started
Official jQuery demos and HTML string replacements.
Example 1 — Official Demo: Replace All Paragraphs
Replace every <p> with a bold element containing “Paragraph.”
Before: <p>Hello</p> <p>cruel</p> <p>World</p>
After: <b>Paragraph.</b> (×3)
Removed <p> nodes lose data/events
Official jQuery API Example 2 pattern
How It Works
jQuery selects all paragraphs, removes each from the DOM, and inserts the parsed HTML string in each location. The return value is the jQuery object of removed <p> elements.
Example 2 — Official Demo: Replace Button with Div
On click, replace each button with a <div> containing the same label text.
jQuery
$( "button" ).on( "click", function() {
$( this ).replaceWith( "<div>" + $( this ).text() + "</div>" );
} );
Click "First": <button> → <div>First</div>
Button removed; cannot be clicked again
Each button replaced independently on click
Official jQuery API Example 1 pattern
How It Works
$( this ) inside the click handler refers to the clicked button. .replaceWith() removes that button and inserts a div with the same text content in its place.
📈 Move, Callback & Unwrap
Existing DOM nodes, dynamic content, and container unwrapping.
Example 3 — Replace with an Existing DOM Element
Click a paragraph to replace it with a <div> already on the page — the div moves, it is not cloned.
jQuery
$( "p" ).on( "click", function() {
$( this ).replaceWith( $( "div" ) );
} );
// The lone <div>Replaced!</div> moves into the clicked paragraph's slot
// Only one div exists — moved, not duplicated
Click any <p>: that paragraph removed
The existing <div> moves into its place
Original div location becomes empty
Official jQuery API Example 3 pattern
How It Works
When newContent is a jQuery object pointing to an element already in the document, jQuery detaches it and inserts it at the replacement location. Event handlers on the moving div survive.
Example 4 — Callback Replacement (Since jQuery 1.4)
Replace each button with a div built from its own text using a callback function.
Before: <div class="container"><div class="inner">…</div>…</div>
After: <div class="inner">Scooby</div> <div class="inner">Dooby</div> …
$removed.attr("class") → "container"
Official jQuery API Example 4 pattern
How It Works
Returning $( this ).contents() from the callback replaces the wrapper with its children. The returned jQuery object from .replaceWith() still references the removed container for follow-up logic.
Applications
🚀 Common Use Cases
Upgrade markup — replace deprecated elements with semantic HTML5 tags.
Click-to-transform — replace a button with a status div after submission.
Move widgets — swap a placeholder with an existing DOM component.
Unwrap containers — remove wrapper divs while keeping children via callback.
Batch replacement — replace all matching nodes with standardized HTML.
Dynamic templates — callback builds unique replacement per element.
🧠 How .replaceWith() Swaps Elements
1
Match elements to remove
jQuery collection identifies old nodes targeted for replacement.
Target
2
Resolve new content
HTML string, jQuery object, or callback return value becomes replacement.
Content
3
Swap in DOM
Each old node removed; new content inserted. Old data/events cleared.
Swap
4
✓
Return removed collection
Original jQuery set of deleted elements returned — not the new content (since 1.9).
Important
📝 Notes
Available since jQuery 1.2; callback form since jQuery 1.4.
Returns the removed jQuery collection — not the inserted replacement.
Since jQuery 1.9, always returns the original unmodified set consistently.
Removed nodes lose jQuery data and event handlers.
Existing DOM nodes used as replacement are moved, not cloned (single-target case).
Replacing a node not connected to a document has no effect since jQuery 1.9.
Pair with .replaceAll() when content-first syntax reads more clearly.
Compatibility
Browser Support
.replaceWith() has been part of jQuery since 1.2+ (callback since 1.4+). It uses standard DOM insertion and removal through jQuery's manipulation layer. Works in all browsers supported by your jQuery build — IE6+ through modern evergreen browsers in legacy jQuery versions, and all current browsers in jQuery 3.x and 4.x.
✓ jQuery 1.2+
jQuery .replaceWith()
Universal DOM replacement API across jQuery 1.x, 2.x, 3.x, and 4.x. Pair with .replaceAll() when content-first syntax fits better.
100%With jQuery loaded
Google ChromeAll versions · Desktop & Mobile
Full support
Mozilla FirefoxAll versions · Desktop & Mobile
Full support
Apple SafariAll versions · macOS & iOS
Full support
Microsoft EdgeAll versions · Chromium & Legacy
Full support
Internet ExplorerIE 6+ · Legacy environments
Full support
OperaAll modern versions
Full support
.replaceWith()Universal
Bottom line: Default choice when you already have the elements to remove selected in a jQuery collection.
Wrap Up
Conclusion
The jQuery .replaceWith() method removes matched elements and inserts new content in one step. Pass an HTML string, DOM node, jQuery object, or callback since 1.4. The method returns the removed jQuery collection — exactly as the official jQuery demos illustrate.
When replacement content is selected first, use .replaceAll() instead. Next up: check element data safely with jQuery.hasData().
Use .replaceWith() when the elements to remove are already selected
Use the callback form for per-element dynamic replacements
Capture the return value when you need metadata from removed nodes
Re-bind events on new elements after batch replacements
Prefer .replaceAll() when starting from replacement content
❌ Don’t
Assume the return value is the new content — it is the removed set
Expect replaced nodes to keep event handlers
Use .replaceWith() when only inner HTML should change — use .html()
Replace nodes detached from the document — no effect since jQuery 1.9
Forget accessibility when replacing interactive controls like buttons
Summary
Key Takeaways
Knowledge Unlocked
Six things to remember about .replaceWith()
The target-first API for swapping DOM elements.
6
Core concepts
1st01
Target first
Direct
Syntax
⇄02
Full swap
Outer node
Replace
fn03
Callback
Since 1.4
Dynamic
↔04
vs replaceAll
Pair API
Compare
←05
Returns old
Removed
Return
1.206
Since 1.2
Core API
Stable
❓ Frequently Asked Questions
.replaceWith(newContent) removes each matched element from the DOM and inserts new content in its place. newContent can be an HTML string, DOM element, array of elements, jQuery object, or callback since 1.4. Returns the original removed jQuery collection. Available since jQuery 1.2.
.replaceWith(newContent) is called on the elements to remove: $('p').replaceWith('<b>Hi</b>'). .replaceAll(target) is called on the replacement: $('<b>Hi</b>').replaceAll('p'). Same DOM result, reversed syntax — target-first vs content-first.
It returns the original jQuery object referring to the elements that were removed — not the new replacement content. Since jQuery 1.9, .replaceWith() always returns the original unmodified set. Useful when you need to inspect or chain operations on the removed nodes before they are garbage-collected.
Yes, since jQuery 1.4. Pass a function and jQuery calls it once per matched element. Return HTML, a DOM element, or jQuery object as the replacement. Inside the function, this refers to the DOM element being replaced.
Removed elements lose all jQuery data and event handlers. The replacement content keeps its own handlers if it already had them. Re-bind events on new elements after replacement when needed.
.html(newContent) replaces inner contents — the outer element stays. .replaceWith(newContent) removes the entire matched element and puts new content in its place. Use html() to change what is inside a div; use replaceWith() to swap the div itself.
Did you know?
Unlike most jQuery manipulation methods that return the modified collection for chaining new operations, .replaceWith() returns the removed elements. That lets you read attributes from the old node after swap — like the official unwrap demo capturing $container.attr( "class" ). Since jQuery 1.9, .replaceWith(), .after(), and .before() consistently return the original set rather than varying behavior based on connectedness.