jQuery .wrapAll() wraps an HTML structure around all elements in the set of matched elements
Syntax and Description
.wrapAll(wrappingElement)
wraps an HTML structure around all elements in the set of matched elements.
wrappingElement
is an HTML snippet,
selector expression, jQuery object, or DOM element
specifying the structure to wrap around the matched elements.
Its return value is the jQuery object, for chaining purposes.
For the following code
<div class="container">
<div class="inner">Hello</div>
<div class="inner">InnerText</div>
</div>
To insert an HTML structure around the inner <div>
elements we can code as follows:
$('.inner').wrapAll('<div class="new" />');
Result:
<div class="container">
<div class="new">
<div class="inner">Hello</div>
<div class="inner">InnerText</div>
</div>/*from ww w . j a va 2 s .com*/
</div>
Wrap with div element
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!-- ww w.j av a 2 s.c o m-->
$("p").wrapAll(document.createElement("div"));
});
</script>
<style>
div { border: 2px solid blue; }
</style>
</head>
<body>
<body>
<p>Hello</p> <p>Hello</p> <p>java2s.com</p>
</body>
</html>
Wrap with border
The following code defines style for div and the style contains border definition. Then it wraps all paragraph with with div. In this way we can add border to paragraph.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!-- ww w. ja va 2 s . c o m-->
$("p").wrapAll("<div></div>");
});
</script>
<style>
div { border: 2px solid blue; }
</style>
</head>
<body>
<body>
<p>Hello</p> <p>Hello</p> <p>Hello</p>
</body>
</html>
WrapAll With More Than One Tag
The following code wrap more than one hard coded element to paragraphs.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!-- w ww . jav a 2s . c o m-->
$("p").wrapAll("<div><b>java2s.com</b></div>");
});
</script>
<style>
div { border: 2px solid blue; }
</style>
</head>
<body>
<body>
<p>Hello</p> <p>Hello</p> <p>Hello</p>
</body>
</html>
Wrap with selected elements
In the following code each element in the matched set would get wrapped with an element.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!-- ww w. j a v a2 s . co m-->
$("p").wrapAll($(".doublediv"));
});
</script>
<style>
.doublediv { color:red; }
</style>
</head>
<body>
<body>
<p>World</p>
<p>World</p>
<div class="doublediv">java 2s .com<div>
</body>
</html>