jQuery Tutorial Tutorials - jQuery .wrap() method

jQuery .wrap() method

The .wrap() method in jQuery is used to wrap a new HTML structure around the matched elements.

jQuery .wrap() method Syntax

.wrap(wrappingElement)
.wrap(function)

wrappingElement specifying the structure to wrap around the matched elements.
function is a callback function returning the HTML content or jQuery object

.wrap(wrappingElement)

example

insert an HTML structure around all the paragraph elements.

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

example

use element to wrap the paragraph

$("p").wrap(document.getElementById('content'));

$("p").wrap( document.createElement( "div" ) );

Try now

.wrap(function)

example

Create a new <div> element to wrap around each matched element. the class name of <div> is corresponding to the text of matched element.
HTML

<div class="container">
  <div class="inner">javascript</div>
  <div class="inner">jquery</div>
</div>

jQuery

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

Result

<div class="container">
  <div class="javascript">
    <div class="inner">javascript</div>
  </div>
  <div class="jquery">
    <div class="inner">jquery</div>
  </div>
</div>
Date:2019-08-25 10:52:53 From:www.Lautturi.com author:Lautturi