Episode 10 of 24
Wrapping and Unwrapping Elements with jQuery
Learn how to wrap elements with new containers and unwrap them using jQuery.
jQuery provides methods to wrap elements in new containers or remove their parent wrappers.
wrap() — Wrap Each Element Individually
// Wrap every paragraph in a div
$("p").wrap("<div class='text-block'></div>");
// Before: <p>Hello</p>
// After: <div class="text-block"><p>Hello</p></div>
wrapAll() — Wrap All Elements Together
// Wrap ALL selected paragraphs in one container
$("p").wrapAll("<section class='content'></section>");
// Before: <p>One</p> <p>Two</p> <p>Three</p>
// After: <section class="content">
// <p>One</p><p>Two</p><p>Three</p>
// </section>
wrapInner() — Wrap the Content Inside
// Wrap the inner content of each element
$("h2").wrapInner("<span class='highlight'></span>");
// Before: <h2>Title</h2>
// After: <h2><span class="highlight">Title</span></h2>
unwrap() — Remove the Parent Wrapper
// Remove the parent element, keeping the children
$("p").unwrap();
// Before: <div class="wrapper"><p>Hello</p></div>
// After: <p>Hello</p>
Practical Examples
// Wrap images in a figure element
$("img").wrap(function() {
let alt = $(this).attr("alt") || "Image";
return '<figure><figcaption>' + alt + '</figcaption></figure>';
});
// Wrap links that open externally
$("a[target='_blank']").wrap("<span class='external-link'></span>");