jQuery wrap() example

jQuery wrap() is used to wrap HTML element around each of the matched elements.

For example,


<div class="innerBox">Ip man vs Iron man</div>
<div class="innerBox">Ip man 2 vs Iron man 2</div>

Wrap it with a div tag that contains a class name of ‘wrapBox’.


$('.innerBox').wrap("<div class='wrapBox'></div>");

The new contents will become :


<div class='wrapBox'>
   <div class="innerBox">Ip man vs Iron man</div>
</div>

<div class='wrapBox'>
   <div class="innerBox">Ip man 2 vs Iron man 2</div>
</div>

Warning
DO NOT wrap with html content


$('.innerBox').wrap("<div class='wrapBox'>TESTING</div>");

Do you expect following?


<div class='wrapBox'>TESTING
   <div class="innerBox">Ip man vs Iron man</div>
</div>

No, the result will be a total replacement. The wrap is only support the html tag, not content.


<div class='wrapBox'>TESTING</div>

Try it yourself


<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<style type="text/css">
	.innerBox{
		padding:8px;
		border:1px solid blue;
		margin:8px;
	}
	.wrapBox{
		padding:8px;
		border:1px solid red;
		margin:8px;
	}
</style>

</head>
<body>
  <h1>jQuery wrap() example</h1>

  <div class="innerBox">Ip man vs Iron man</div>
  
  <div class="innerBox">Ip man 2 vs Iron man 2</div>
  
  <p>
  <button id="wrapButton">wrap()</button>
  <button id="reset">reset</button>
  </p>
  
<script type="text/javascript">
	
    $("#wrapButton").click(function () {
		
	  $('.innerBox').wrap("<div class='wrapBox'></div>");
	  
    });
	
	$("#reset").click(function () {
	  location.reload();
    });
	
</script>
</body>
</html>

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Zkiwi
Guest
Zkiwi

Thanks for tips! I have a problem when i using this Jquery.

have a div:

<div class="wrapme">some text</div>

and i wrap it:

$('.wrapme').wrap('<div style="display:none" />');

result:

<div style="display:none"><div class="wrapme">some text</div></div>
<div class="wrapme">some text</div>

–> my div is duplicated. Why that? Thanks men!

Zkiwi
Guest
Zkiwi

Thanks for tips! I have a problem when i using this Jquery.

have a div:

some text

and i wrap it:
$(‘.wrapme’).wrap(”);

result:

some text
some text

–> my div is duplicated. Why that? Thanks men!