jQuery Wrap/Unwrap
The jQuery wrap()
, wrapAll()
, wrapInner()
, and unwrap()
methods are used to dynamically wrap or unwrap HTML elements. These methods help in modifying the structure of the DOM without replacing existing elements.
Key Topics
Using wrap()
The wrap()
method wraps the selected elements individually in a specified structure.
$(".box").wrap("<div class='wrapper'></div>");
Explanation: This code wraps each element with the class box
in a <div>
with the class wrapper
.
Using wrapAll()
The wrapAll()
method wraps all selected elements together in a single wrapper.
$(".box").wrapAll("<div class='wrapper'></div>");
Explanation: This code wraps all elements with the class box
in a single <div>
with the class wrapper
.
Using wrapInner()
The wrapInner()
method wraps the inner content of the selected elements with a specified structure.
$(".box").wrapInner("<div class='inner-wrapper'></div>");
Explanation: This code wraps the inner content of each element with the class box
in a <div>
with the class inner-wrapper
.
Using unwrap()
The unwrap()
method removes the immediate parent of the selected elements, leaving their content intact.
$(".box").unwrap();
Explanation: This code removes the parent wrapper around elements with the class box
.
Example: Wrapping and Unwrapping
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Wrap/Unwrap Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
<button id="wrapButton">Wrap Boxes</button>
<button id="unwrapButton">Unwrap Boxes</button>
<script>
$(document).ready(function() {
$("#wrapButton").click(function() {
$(".box").wrap("<div class='wrapper'></div>");
});
$("#unwrapButton").click(function() {
$(".box").unwrap();
});
});
</script>
</body>
</html>
Explanation: This example demonstrates how to wrap elements dynamically with wrap()
and remove the wrapper using unwrap()
when a button is clicked.
Key Takeaways
- Individual Wrapping: Use
wrap()
to wrap each selected element separately. - Group Wrapping: Use
wrapAll()
to wrap all selected elements in a single wrapper. - Inner Content Wrapping: Use
wrapInner()
to wrap the inner content of elements. - Removing Wrappers: Use
unwrap()
to remove the parent wrapper of elements.