views:

152

answers:

2

Say I have 5 strong elements, and I want to wrap them in div elements, in groups of 2 using jQuery.

Example:

<!--original markup-->
<strong>I AM STRONG</strong>
<strong>I AM STRONG</strong>
<strong>I AM STRONG</strong>
<strong>I AM STRONG</strong>
<strong>I AM STRONG</strong>

Becomes

<!-- new markup -->
<div>
    <strong>I AM STRONG</strong>
    <strong>I AM STRONG</strong>
</div>
<div>
    <strong>I AM STRONG</strong>
    <strong>I AM STRONG</strong>
</div><div>
    <strong>I AM STRONG</strong>
</div>

What would be the best way to do this? I have tried a few things but they were problematic. The strong elements can not have a fixed height. Also, these elements are for example only.

How would I write a jQuery loop to do this?

Thank you

Edit There is not a fixed number of elements.

A: 

You could use the :odd to select every other element, then .prev to get the even element.

$('strong:odd').each(function(){
  var divElement = $('<div></div>').append($(this).prev(), $(this));
  // Now add the divElement to a new container?
});
Matt
+4  A: 

I'd probably just loop two at a time, wrapping each pair as i go...

var elems = $("strong");
for (var i=0; i<elems.length; i+=2)
{
  elems.slice(i,i+2)   // split off a pair
    .wrapAll("<div>"); // wrap it
}
Shog9
Clever code... Thanks Shog9!
alex