From jQuery JavaScript Library
« Back to Manipulation
wrap( html )
Wrap all matched elements with a structure of other elements.
This wrapping process is most useful for injecting additional structure into a document, without ruining the original semantic qualities of a document.
This works by going through the first element provided (which is generated, on the fly, from the provided HTML) and finds the deepest ancestor element within its structure -- it is that element that will enwrap everything else.
This does not work with elements that contain text. Any necessary text must be added after the wrapping is done.
Arguments:| html | String | |
|---|
| A string of HTML that will be created on the fly and wrapped around the target. |
Examples:| Name | Type |
Wraps a newly created div around all paragraphs.
$("p").wrap("<div class='wrap'></div>");
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="../jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("p").wrap("<div class='wrap'></div>");
});
</script>
<style>.wrap { background:#bbf; }</style>
</head>
<body>
<p>Test Paragraph.</p>
</body>
</html>
Wraps a newly created tree of objects around each span.
$("span").wrap("<div><div><p><em><b></b></em></p></div></div>");
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="../jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("span").wrap("<div><div><p><em><b></b></em></p></div></div>");
});
</script>
<style>
div { border:2px blue solid; margin:2px; padding:2px; }
p { background:yellow; margin:2px; padding:2px; }
</style>
</head>
<body>
<span>Span Text</span>
<span>Another One</span>
</body>
</html>
wrap( elem )
Wrap all matched elements with a structure of other elements.
Arguments:| elem | Element | |
|---|
| A DOM element that will be wrapped around the target. |
Examples:| Name | Type |
Wraps an element with id of "content" around all paragraphs.
$("p").wrap(document.getElementById('content'));
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="../jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("p").wrap(document.getElementById('content'));
});
</script>
<style>#content { background:#9f9; }</style>
</head>
<body>
<p>Test Paragraph.</p><div id="content"></div>
</body>
</html>
Wraps a jQuery object (in this case a div) around all paragraphs.
$("p").wrap($("<div>"));
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="../jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("p").wrap($("<div>"));
});
</script>
<style>div { background:#f99; }</style>
</head>
<body>
<p>Test Paragraph.</p>
<p>Another Paragraph.</p>
</body>
</html>