jQuery wrapAll() Method
The wrapAll() method in jQuery is used to wrap a single HTML structure around all elements matched by a selector. It wraps a specified HTML structure around the entire set of matched elements as a single unit.
Note: If you want to wrap an HTML structure around each element in a selected set of elements, wrap() is the appropriate method to use.
Syntax
Following is the syntax of the wrapAll() method in jQuery −
$(selector).wrapAll(wrappingElement)
Parameters
Following is the syntax of wrapAll() method in jQuery −
- wrappingElement: Specifies what HTML element(s) to wrap around each selected element. The possible values could be: HTML elements, DOM elements, jQuery objects.
Example 1
Using wrap() method with HTML element:
In the following exmaple, we are wrapping a single HTML structure (<div>) around all <p> elements using the wrapAll() method −
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").wrapAll("<div></div>");
});
});
</script>
<style>
div{
border: 2px solid green;
}
</style>
</head>
<body>
<p>Paragraph element.</p>
<p>This is another Paragraph element.</p>
<button>Click me!</button>
</body>
</html>
When we click the button, <div> element will be wrapped around all <p> elements as a single unit and highlighted with green solid border.
Example 2
Using wrap() method with DOM element:
This is similar to the first example, this one wraps all <p> elements with a <div> element −
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$('p').wrapAll(document.createElement('div'));
});
});
</script>
<style>
div{
border: 2px solid green;
}
</style>
</head>
<body>
<p>Paragraph element.</p>
<p>This is another Paragraph element.</p>
<h3>Heading element.<h3>
<button>Click me!</button>
</body>
</html>
After clicking the button, <div> element will be wrapped around all <p> elements and highlighted with green solid border.
Example 3
Using wrap() method with jQuery object:
Here, we are wrapping all <p> elements with a <div> element −
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$('p').wrapAll($('<div></div>'));
});
});
</script>
<style>
div{
border: 2px solid green;
}
</style>
</head>
<body>
<p>Paragraph element.</p>
<p>This is another Paragraph element.</p>
<h3>Heading element.<h3>
<button>Click me!</button>
</body>
</html>
After clicking the button, <div> element will be wrapped around all <p> elements and highlighted with green solid borders.