Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to create wrapper div around two other divs with jQuery?
To create wrapper div around two other divs, use the wrapAll() method. The wrapAll() method wraps a single HTML structure around all matched elements in the set. This is particularly useful when you want to group multiple elements together within a common container.
Syntax
The basic syntax of the wrapAll() method is −
$(selector).wrapAll(wrappingElement)
Where wrappingElement can be an HTML string, DOM element, or jQuery object that will serve as the wrapper.
Example
You can try to run the following code to create wrapper div around two other divs with jQuery −
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#button3").click(function(){
$('.demo, .demo2').wrapAll('<div class="demo3"></div>');
});
});
</script>
<style>
div {
background-color: yellow;
margin: 10px;
padding: 10px;
border: 1px solid #ccc;
}
.demo3 {
background-color: lightblue;
border: 2px solid blue;
}
button {
margin: 10px;
padding: 8px 16px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
</style>
</head>
<body>
<div class="demo">
<h2>First Div</h2>
<p>This is demo text in first div.</p>
<p>Content 1</p>
</div>
<div class="demo2">
<h2>Second Div</h2>
<p>This is demo text in second div.</p>
<p>Content 2</p>
</div>
<button id="button3">Wrap All Divs</button>
</body>
</html>
In this example, when you click the "Wrap All Divs" button, both the .demo and .demo2 divs will be wrapped inside a new div with class demo3. The jQuery selector $('.demo, .demo2') targets both elements, and wrapAll() creates a single wrapper around them with a light blue background and blue border.
Alternative Approach
You can also create a wrapper div around adjacent elements using different selectors −
// Wrap all divs with class 'content'
$('.content').wrapAll('<div class="container"></div>');
// Wrap specific elements by their IDs
$('#div1, #div2').wrapAll('<div class="wrapper"></div>');
Conclusion
The wrapAll() method is an efficient way to wrap multiple elements with a single container div. This technique is commonly used for grouping related content, applying styling to multiple elements as a unit, or organizing page structure dynamically. Remember that wrapAll() moves all matched elements to the location of the first matched element before wrapping them.
