jQuery: wrapping elements and text

jQuery provides two useful methods for wrapping elements: wrap() and wrapInner(). The former wraps the entire element with another HTML element, whereas the latter wraps its contents. Both methods accepts a literal HTML element as their sole parameter, for example '<div></div>'. In this post I'm going to show you a couple of practical applications of these methods. Suppose for example that we have a series of HTML elements like this:

<div>Test 1</div>
<div>Test 2</div>
<div>Test 3</div>

We want to wrap the text content of each element with an HTML heading. In this case, we'll use wrapInner():

$('div').wrapInner('<h2></h2>');

Now let's test wrap(). Suppose that we want to enclose each element within a div element with a CSS class named evident:

div.evident {
 background: #ffc;
 border: 1px solid #aaa;
 padding: 0.5em;
 width: 15em;
 margin: 1em;
}

We can use wrap() as follows:

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

You can see the final result below.

wrapInner() in Internet Explorer

Some versions of Internet Explorer (mainly the 6th) don't fully support the wrapInner() method, especially when it occurs inside a jQuery loop (such as .each()):

$('div').each(function() {
  
  var $div = $(this);
  $div.wrapInner('<h2></h2>');
});

This problem occurs sometimes but it's very annoying. In order to fix it, you should start your jQuery selection from the parent element or avoid the combination of this method with loops.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.