How jQuery wrapInner Modifies the DOM
The jQuery .wrapInner() method is a DOM manipulation
function designed to enclose the internal content of each matched
element inside a specified HTML structure. This article explains how
.wrapInner() alters the Document Object Model tree, how it
handles child nodes and text, and how it differs from other jQuery
wrapping methods.
How .wrapInner() Works
When .wrapInner() is called on a jQuery selection, it
targets the contents inside each element rather than the element itself.
The method takes an HTML string, selector expression, jQuery object, or
DOM element as an argument to serve as the wrapper.
During execution, .wrapInner() performs the following
sequence:
- Identifies all child nodes of the target element, including element nodes, text nodes, and whitespace.
- Clones or creates the specified wrapper structure.
- Inserts the wrapper directly inside the target element.
- Moves all existing child nodes into the innermost element of the new wrapper structure.
DOM Tree Transformation Example
Consider the following initial HTML structure:
<div class="container">
Hello <strong>World</strong>!
</div>Applying the .wrapInner() method:
$('.container').wrapInner('<div class="inner-box"></div>');The resulting DOM structure becomes:
<div class="container">
<div class="inner-box">
Hello <strong>World</strong>!
</div>
</div>The parent element (.container) remains in its original
position in the document hierarchy. Its child nodes—the text node
"Hello ", the <strong> element, and the
text node "!"—are preserved and relocated inside the new
.inner-box wrapper.
Behavior with Multiple Target Elements
When .wrapInner() is applied to a selection containing
multiple elements, it executes independently for each element in the
set. A fresh instance of the wrapper is injected inside each targeted
parent:
// Wraps the inner contents of every list item individually
$('li').wrapInner('<span class="highlight"></span>');Each <li> element receives its own
<span class="highlight"> containing that specific
list item's original inner content.
Using Functions as Wrappers
The method also accepts a callback function that returns markup dynamically:
$('.card').wrapInner(function(index) {
return '<div class="content-wrapper-' + index + '"></div>';
});The function executes once per element in the set, allowing the wrapper structure to vary based on the index or the element's current state.
Distinction from .wrap() and .wrapAll()
Understanding how .wrapInner() modifies the DOM requires
distinguishing it from related jQuery methods:
.wrapInner(): Places the wrapper inside the target element, surrounding its children..wrap(): Places the wrapper around each matched element itself, moving the target into the wrapper..wrapAll(): Takes the entire collection of matched elements and moves them into a single, shared wrapper.