A callback function returning the HTML content or jQuery object to wrap around the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.

The .wrapAll() function can take any string or object that could be passed to the $() function to specify a DOM structure. This structure may be nested several levels deep, but should contain only one inmost element. The structure will be wrapped around all of the elements in the set of matched elements, as a single group.

Consider the following HTML:

1

2

3

4

<divclass="container">

<divclass="inner">Hello</div>

<divclass="inner">Goodbye</div>

</div>

Using .wrapAll(), we can insert an HTML structure around the inner <div> elements like so:

1

$( ".inner" ).wrapAll( "<div class='new' />");

The new <div> element is created on the fly and added to the DOM. The result is a new <div> wrapped around all matched elements:

1

2

3

4

5

6

<divclass="container">

<divclass="new">

<divclass="inner">Hello</div>

<divclass="inner">Goodbye</div>

</div>

</div>

Examples:

Wrap a new div around all of the paragraphs.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

<!doctype html>

<htmllang="en">

<head>

<metacharset="utf-8">

<title>wrapAll demo</title>

<style>

div{

border:2px solid blue;

}

p{

background: yellow;

margin:4px;

}

</style>

<scriptsrc="https://code.jquery.com/jquery-1.10.2.js"></script>

</head>

<body>

<p>Hello</p>

<p>cruel</p>

<p>World</p>

<script>

$( "p" ).wrapAll( "<div></div>" );

</script>

</body>

</html>

Demo:

Wraps a newly created tree of objects around the spans. Notice anything in between the spans gets left out like the <strong> (red text) in this example. Even the white space between spans is left out. Click View Source to see the original html.