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 wrap and unwrap HTML control with a div dynamically using jQuery?
To wrap HTML control, use the wrap() method and unwrap() method to unwrap HTML control. The wrap() method wraps each selected element with the specified HTML element, while unwrap() removes the parent element of the selected elements.
Syntax
The basic syntax for wrapping and unwrapping elements −
// Wrap elements $(selector).wrap(wrappingElement); // Unwrap elements $(selector).unwrap();
Example
You can try to run the following code to wrap and unwrap HTML control with a div dynamically using 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(){
$("#button1").click(function(){
$("p").wrap("<div></div>");
});
$("#button2").click(function(){
$("p").unwrap();
});
});
</script>
<style>
div {
background-color: lightgray;
padding: 10px;
margin: 5px;
border: 2px solid #333;
border-radius: 5px;
}
p {
margin: 0;
font-size: 16px;
}
button {
margin: 10px 5px;
padding: 8px 16px;
font-size: 14px;
cursor: pointer;
}
</style>
</head>
<body>
<p>This is demo text.</p>
<p>This is another text.</p>
<button id="button1">Wrap with Div</button>
<button id="button2">Unwrap</button>
</body>
</html>
How it works
When you click the Wrap with Div button, each paragraph element gets wrapped with a <div> element, which applies the gray background styling with border and padding. When you click the Unwrap button, the div wrapper is removed, returning the paragraphs to their original state without any additional styling.
The wrap() method creates a separate wrapper div for each paragraph element, so two paragraphs will result in two separate wrapped divs. The unwrap() method removes only the immediate parent element of the selected elements.
Additional Wrapping Methods
jQuery also provides other related wrapping methods −
// Wrap all elements together in a single wrapper
$(selector).wrapAll("<div></div>");
// Wrap the content inside each element
$(selector).wrapInner("<span></span>");
Conclusion
The jQuery wrap() and unwrap() methods provide a simple and powerful way to dynamically add or remove wrapper elements around HTML controls. These methods are particularly useful for applying conditional styling, creating dynamic layouts, or temporarily grouping elements for specific functionality.
