jQuery Wrap All Elements in a Single Element
This article explains how to group multiple matching DOM elements inside a single parent container using jQuery. You will learn the primary method used for this operation, examine standard code examples demonstrating its implementation, and understand how the method handles both adjacent and non-adjacent elements in the DOM tree.
To wrap all elements matching a selector inside a single wrapper
element, use jQuery’s .wrapAll() method. This is different
from the standard .wrap() method, which wraps each matched
element individually in its own separate container.
Syntax
$(selector).wrapAll(wrappingElement);The wrappingElement parameter can be an HTML snippet, a
selector expression, a jQuery object, or a DOM element.
Basic Example
Consider the following HTML structure where multiple paragraph elements share a common class:
<p class="highlight">Paragraph 1</p>
<p class="highlight">Paragraph 2</p>
<p class="highlight">Paragraph 3</p>To enclose all of these paragraphs inside a single
<div class="container"></div>, execute the
following jQuery code:
$('.highlight').wrapAll('<div class="container"></div>');After the code runs, the DOM is updated to:
<div class="container">
<p class="highlight">Paragraph 1</p>
<p class="highlight">Paragraph 2</p>
<p class="highlight">Paragraph 3</p>
</div>Behavior with Non-Adjacent Elements
If the elements matched by the selector are spread across different
parts of the document or separated by other sibling elements,
.wrapAll() gathers all matched elements together.
The wrapper element is placed at the position of the first matching element in the DOM, and all subsequent matching elements are moved from their original locations and appended into that single wrapper. Any elements between the matching items that were not selected remain outside the wrapper.