jQuery wrap()

jQuery wrap() method wraps the specified HTML elements around each selected element.

Syntax:

$(selector).wrap(wrappingElement,function(index))

WrappingElement:

  • It is a compulsory parameter.
  • It is used to specify the HTML elements to be wrapped around each selected element.
  • It can accept HTML elements, jQuery objects, and DOM elements as a value.

Function: It is an optional function to return the wrapping element.

Index: The index is passed as an argument of the function to specify the index position of the element in the set.

Example1:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").wrap("<div></div>");
});
});
</script>
<style>
div{background-color: turquoise;width: 200px;
height: 80px;
margin: 5px;
}
</style>
</head>
<body>
<p>Hello Guys!</p>
<button>Wrap</button>
</body>
</html>

Example2:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").wrap("<div></div>");
});
});
</script>
<style>
div{background-color: turquoise;width: 120px;
height: 120px;
margin: 5px;padding:2px; border:2px solid #666;border-radius:120px;
}
</style>
</head>
<body>
<p>Hello Guys!</p>
<button>Wrap</button>
</body>
</html>