.wrap()

In this chapter you will learn:

  1. Syntax and Description for .wrap()

Syntax and Description

.wrap() wraps an HTML structure around each element in the set of matched elements.

  • .wrap(wrappingElement)
    wrappingElement: An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the matched elements
  • .wrap(wrappingFunction)
    wrappingFunction: A callback function that generates a structure to wrap around the matched elements

Its return value is the jQuery object, for chaining purposes.

Consider the following HTML 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 use the following code:

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

The results are:

<div class="container">/*from j ava  2s .  c o m*/
 <div class="new">
 <div class="inner">Hello</div>
 </div>
 <div class="new">
 <div class="inner">InnerText</div>
 </div>
</div>

If we specify a callback function for .wrap function, the call function will be called for every matched element.

It should return a DOM element, a jQuery object, or an HTML snippet in which to wrap the corresponding element. For example:

$('.inner').wrap(function() {
 return '<div class="' + $(this).text() + '" />';
});

Results:

<div class="container">//from j a  v a 2  s  . c  om
 <div class="Hello">
 <div class="inner">Hello</div>
 </div>
 <div class="InnerText">
 <div class="inner">InnerText</div>
 </div>
</div>

Next chapter...

What you will learn in the next chapter:

  1. Syntax and Description for .wrapAll()
  2. Wrap with div element
  3. Wrap with border
  4. WrapAll With More Than One Tag
  5. Wrap with selected elements