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>
Thanks for tips! I have a problem when i using this Jquery.
have a div:
and i wrap it:
result:
–> my div is duplicated. Why that? Thanks men!
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!