jQuery .wrap() wraps an HTML structure around matched elements

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">
 <div class="new">
 <div class="inner">Hello</div>
 </div>/* www  . j  a  v  a2  s . c o m*/
 <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">
 <div class="Hello">
 <div class="inner">Hello</div>
 </div>/*ww w  .jav a2 s .  co  m*/
 <div class="InnerText">
 <div class="inner">InnerText</div>
 </div>
</div>




















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities