Wrapping Elements

Another type of insertion into an HTML document involves wrapping a new element around one or more elements. jQuery defines three wrapping functions: wrap() wraps each of the selected elements, wrapInner() wraps the contents of each selected element, and wrapAll() wraps the selected elements as a group. These methods are usually passed a newly created wrapper element or a string of HTML used to create a wrapper. The HTML string can include multiple nested tags, if desired, but there must be a single innermost element. If you pass a function to any of these methods, it will be invoked once in the context of each element (with the element index as its only argument) and should return the wrapper string, Element, or jQuery object. Here are some examples:

// Wrap all <h1> tags with <i> tags
// Produces <i><h1>...</h1></i>
$("h1").wrap(document.createElement("i")); 
// Wrap the content of all <h1> tags. 
// Produces <h1><i>...</i></h1>
$("h1").wrapInner("<i/>");
// Wrap the first paragraph in an anchor and div
$("body>p:first")
    .wrap("<a name='f'><div class='first'></div></a>");
// Wrap all the other paragraphs in another div
$("body>p:not(:first)")
    .wrapAll("<div class='rest'></div>");

Get jQuery Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.