Javascript – Can you get a subset of elements in jQuery as per a grouping amount

javascriptjqueryloops

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.

Best Solution

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
}