jQuery API

.wrap()

.wrap( wrappingElement ) Returns: jQuery

Description: Wrap an HTML structure around each element in the set of matched elements.

  • version added: 1.0.wrap( wrappingElement )

    wrappingElementAn HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the matched elements.

  • version added: 1.4.wrap( function(index) )

    function(index)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 .wrap() function can take any string or object that could be passed to the $() factory function to specify a DOM structure. This structure may be nested several levels deep, but should contain only one inmost element. A copy of this structure will be wrapped around each of the elements in the set of matched elements. This method returns the original set of elements for chaining purposes.

Consider the following HTML:

<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

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

$('.inner').wrap('<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 each matched element:

<div class="container">
  <div class="new">
    <div class="inner">Hello</div>
  </div>
  <div class="new">
    <div class="inner">Goodbye</div>
  </div>
</div>

The second version of this method allows us to instead specify a callback function. This callback function will be called once for every matched element; it should return a DOM element, jQuery object, or HTML snippet in which to wrap the corresponding element. For example:

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

This will cause each <div> to have a class corresponding to the text it wraps:

<div class="container">
  <div class="Hello">
    <div class="inner">Hello</div>
  </div>
  <div class="Goodbye">
    <div class="inner">Goodbye</div>
  </div>
</div>

Examples:

Example: Wrap a new div around all of the paragraphs.

<!DOCTYPE html>
<html>
<head>
  <style>

  div { border: 2px solid blue; }
  p { background:yellow; margin:4px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>Hello</p>
  <p>cruel</p>
  <p>World</p>
<script>$("p").wrap("<div></div>");</script>

</body>
</html>

Demo:

Example: 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.

<!DOCTYPE html>
<html>
<head>
  <style>

  div { border:2px blue solid; margin:2px; padding:2px; }
  p { background:yellow; margin:2px; padding:2px; }
  strong { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <span>Span Text</span>
  <strong>What about me?</strong>
  <span>Another One</span>
<script>$("span").wrap("<div><div><p><em><b></b></em></p></div></div>");</script>

</body>
</html>

Demo:

Example: Wrap a new div around all of the paragraphs.

<!DOCTYPE html>
<html>
<head>
  <style>

  div { border: 2px solid blue; }
  p { background:yellow; margin:4px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>Hello</p>
  <p>cruel</p>
  <p>World</p>
<script>$("p").wrap(document.createElement("div"));</script>

</body>
</html>

Demo:

Example: Wrap a jQuery object double depth div around all of the paragraphs. Notice it doesn't move the object but just clones it to wrap around its target.

<!DOCTYPE html>
<html>
<head>
  <style>

  div { border: 2px solid blue; margin:2px; padding:2px; }
  .doublediv { border-color:red; }
  p { background:yellow; margin:4px; font-size:14px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>Hello</p>
  <p>cruel</p>
  <p>World</p>
  <div class="doublediv"><div></div></div>
<script>$("p").wrap($(".doublediv"));</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .wrap() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .wrap()? Report it to the jQuery core team.

Found a problem with this documentation? Report it on the GitHub issue tracker

  • http://twitter.com/michl86 michl86

    wrap (and wrapAll) only works if the element has a parentNode. you should remind this when creating new structures. the creation of a simple list with anchors is a good example.

    var names = ["Michael", "Arnold", "Andreas"];

    var list = $("<ul />", {
        "id": "news"
    });

    $(names).each(function (index, element) {
        $("<a />", {
           href:"http://www.google.de",
           text: element
        })
         .wrap("<li />");
         .appendTo(list)
    });

    list.appendTo("#cont");

    this wont work, because the a has no parent element. you have to switch the function order.

    $(names).each(function (index, element) {
        $("<a />", {
           href:"http://www.google.de",
           text: element
        })
         .appendTo(list)
         .wrap("<li />");
    });

    then every anchor has already the ul as parent and wrap can do it’s job. it would be nice if this could be changed in the jquery core, because the first snippet is much more easier to read.

    • Anonymous

      I don’t think that it’s a bug or something like that. You can’t wrap element if it’s not in DOM structure and this way is quite logical.

    • LukeMaurer

      Actually, even if jQuery added the ability you suggest to wrap a parentless element (presumably by simply giving it a parent), your first example wouldn't work, for the reason buzz mentions above — you'd wind up wrapping the element only to unwrap it again when you append it.

      CTTOI, though, you could always do as buzz suggests, and put in a “.parent()” before the “.appendTo(list)”; in fact I think doing so would make it a little clearer what's going on. So yeah, I agree that wrapping orphans is a good idea.

      (/me hopes that last sentence never comes up when he runs for office :-D )

  • Buczkó Mátyás (buzz)

    Don't forget that if you create an element, wrap something around it and then insert it to the DOM structure you will lose the wrapped object as parent.

    If you do it like this:
    $('').wrap(“<li/>”).parent().appendTo(ul);

    It will work. Any unlinked element can be wrapped, but don't forget to step one level up before inserting it to the DOM!

    Unlinked elements are node trees themselves.

    If there is any bug, it could be questioned, why doesn't the function return with the set of the new parent elements instead of the input set (like clone). But of course it could lead to other problems.

    • carloslm

      It's better to add the element to the DOM first and then wrap it:

      $(document.createTextNode('Hello'))
      .prependTo('body')
      .wrap('<h1><i><del>');

  • http://twitter.com/mspreij M Spreij

    Note that .wrap('span') has an *entirely* different result than .wrap(''). The latter will wrap the object in tags, the first seems to look for the first span tag in the document and use a copy of that, including any content of that span tag. Quite confusing if you don't know this :-)

    • http://twitter.com/wconcepts Colin Williams

      $.wrap('<span>') would be more appropriate. Remember that the argument is “An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the matched elements.”

      … Actually, I think your comment made that point but suffered from the <span> being interpreted in your comment and not displayed..

  • scottSEA

    So after the wrap operation, does the returned jQuery object include the new wrapping elements or just the original element?

    • AnupamKhurana

      It returns the original element.

  • Laxmi Karavadi

    Can the wrap function be used for wrapping more than one elements ie. all the divs in the body should be surrounded by 1 wrapper, something lke a border to all the divs?

    • Neil

      That would be .wrapInner()

  • AnupamKhurana

    It returns the original element.

  • hitautodestruct

    On new created elements such as:
    $('<img>',{ src: 'mypic.gif' });

    The element must be injected into the DOM before it is wrapped i.e:
    $('<img>',{ src: 'mypic.gif' }).appendTo('#mylist').wrap('<li>');

    And NOT!
    $('<img>',{ src: 'mypic.gif' }).wrap('</li><li>').appendTo('#mylist');</li>

    • Yopraag

      Correction to the bad example:
      $('<img>',{ src: 'mypic.gif' }).wrap('<li>').appendTo('#mylist');</li>