jQuery wrap() Function
An often overlooked feature of the jQuery library is the jQuery.wrap() function which wraps all of the selected elements with an html structure. This is really helpful when we want to ensure elements have a wrapper element with certain styles. There are a number of ways to invoke the function but this is my usual approach:
Imagine you have the following markup:
<div> <div class="btn"></div> <div class="btn"></div> <div class="btn"></div> </div>
Wrap let’s us target certain elements on the page and then wrap each with some extra html. From jQuery’s documentation on wrap:
The .wrap()
function can take any string 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
$('.btn').wrap('<div class="btn-wrapper"></div>');
Yields the following DOM structure:
<div> <div class="btn-wrapper"> <div class="btn"></div> </div> <div class="btn-wrapper"> <div class="btn"></div> </div> <div class="btn-wrapper"> <div class="btn"></div> </div> </div>