.wrapAll()S2C Home « Manipulation « .wrapAll()

DOM insertion around elements.

Description

The .wrapAll() method is used to wrap a DOM element, HTML string, jQuery object or selector expression around all elements in the matched set.

  • Use the .wrap() method to wrap a DOM element, HTML string, jQuery object or selector expression around each element in the matched set.
  • Use the .wrapInner() method to wrap a DOM element, HTML string, jQuery object or selector expression around the contents of each element in the matched set.
  • The .wrapAll() method accepts any string or object that could be passed to the $() factory function to specify a DOM structure:
    1. This structure may be nested several levels deep, but should contain only one innermost element.
    2. A copy of this structure will be wrapped around the content of each element in the matched set.
    3. The .wrapAll() method returns the original matched set for chaining purposes.
    4. When passing a HTML string, use well formed HTML with correctly closed tags.

Syntax

Signature Description
.wrapAll( wrappingElement )Wrap a DOM element, HTML string, jQuery object or selector expression around all elements in the matched set.

Parameters

Parameter Description Type
wrappingElementA DOM element, HTML string, jQuery object or selector expression.Element,
HTMLstring or
jQuery

Return

A jQuery object containing the matched set before the call to the .wrapAll() method.

.wrapAll( wrappingElement ) ExampleTop

Wrap a DOM element, HTML string, jQuery object or selector expression around all elements in the matched set.

In the example below when the button is pressed the first time, we wrap a 'div' element around the 'p' elements below. The CSS for the 'div4' and 'div5' ids and the html for the text we are wrapping is displayed first.


#main #div4, #main #div5 {
  background-color: silver;
  padding: 10px;
  border: 1px solid black;
}
#main #div5 {
  background-color: cyan;
}
...
<div id="div4">
  <p class="football">Football is a great game.</p>
  <p class="football">Cricket is a great game.</p>
  <p class="football">Baseball is a great game.</p>
</div>

Football is a great game.

Cricket is a great game.

Baseball is a great game.



$(function(){
  $('#btn5').one('click', function() {
    $('.football').wrapAll('<div id="div5"></div>'); 
  });
});

Press the button below to action the above code: