Wrapping and Unwrapping Elements
In this page:
wrap()
The wrap() method inserts a copy of the given HTML structure around each element in the current selection individually. If you wrap three elements, each one gets its own separate wrapper, not one shared wrapper.
Example: wrap()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
.box { border: 2px solid #333; padding: 8px; margin: 4px 0; }
</style>
</head>
<body>
<p class="item">One</p><p class="item">Two</p>
<script>
$(".item").wrap("<div class='box'></div>");
</script>
</body>
</html>
wrapAll()
wrapAll() places all selected elements inside a single shared wrapper instead of giving each one its own. This is useful when a group of elements needs to be treated as one unit, like several columns wrapped in a single row container.
Example: wrapAll()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
.group { border: 2px solid #333; padding: 8px; }
</style>
</head>
<body>
<p class="item">One</p><p class="item">Two</p>
<script>
$(".item").wrapAll("<div class='group'></div>");
</script>
</body>
</html>
wrapInner()
wrapInner() wraps the contents inside each selected element, rather than wrapping the element itself. The element keeps its original position, but a new wrapper appears just inside it, around its existing children.
Example: wrapInner()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box">Content</div>
<script>
$("#box").wrapInner("<em></em>");
</script>
</body>
</html>
unwrap()
unwrap() removes an element's immediate parent while keeping the selected elements themselves in place. It's effectively the reverse of wrap(), useful for undoing a wrapper you no longer need.
Example: unwrap()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div class="box"><p id="text">Content</p></div>
<script>
$("#text").unwrap();
</script>
</body>
</html>
Wrapping Multiple Items
Wrapping is useful for grouping elements into a new structure, such as wrapping a set of form fields in a fieldset-like container for styling. Because wrap() operates per-element, it's the right tool when each item needs its own independent wrapper.
Example: Wrapping Multiple Items
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input name="first"><input name="last">
<script>
$("input").wrapAll("<fieldset></fieldset>");
</script>
</body>
</html>
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: