Wrap HTML Around an Element Using jQuery

Wrapping an HTML structure around a specific element in jQuery is a common task accomplished primarily using the .wrap() method, alongside related functions like .wrapAll() and .wrapInner(). This guide explains how these methods work, demonstrates their syntax with code examples, and details how to choose the right approach for your specific DOM manipulation needs.

Using the .wrap() Method

The .wrap() method encloses each matched element individually with the specified HTML structure, element, or jQuery object.

Syntax

$(selector).wrap(wrappingElement);

Example: Wrapping an Element with a <div>

Suppose you have the following HTML paragraph:

<p class="target">This is a paragraph.</p>

To wrap this paragraph inside a div with a class of container, use:

$('.target').wrap('<div class="container"></div>');

Result:

<div class="container">
    <p class="target">This is a paragraph.</p>
</div>

If multiple elements match the selector, .wrap() wraps each one in its own separate container:

// Wraps each <span> in its own separate <strong> tag
$('span').wrap('<strong></strong>');

Using the .wrapAll() Method

When you have multiple elements and want to place all of them inside a single, shared parent container, use .wrapAll().

Example:

<p class="item">First paragraph</p>
<p class="item">Second paragraph</p>
$('.item').wrapAll('<div class="wrapper"></div>');

Result:

<div class="wrapper">
    <p class="item">First paragraph</p>
    <p class="item">Second paragraph</p>
</div>

Note: If the elements to be wrapped are not siblings in the DOM, .wrapAll() will move them so they become siblings inside the new wrapper.


Using the .wrapInner() Method

If you need to wrap the contents inside an element rather than placing a container around the element itself, use .wrapInner().

Example:

<div class="card">Card content goes here.</div>
$('.card').wrapInner('<div class="card-body"></div>');

Result:

<div class="card">
    <div class="card-body">Card content goes here.</div>
</div>

Using Callback Functions

The .wrap() and .wrapInner() methods also accept a callback function. This is useful when you need to dynamically determine the wrapper based on an element's index or attributes.

$('p').wrap(function(index) {
    return '<div class="wrapper-' + index + '"></div>';
});

This dynamically assigns a unique wrapper class to each paragraph depending on its position in the matched set.