I have really been struggling with this, and also struggling how to explain the question in a forum.

I want jQuery to detect for a class 'x' or 'y' (both need to be possible) which then results in those divs:
(a) being grouped together inside a new div named either 'x' or 'y'
(b) the last element with x or y will have the class names used as the new wrapper div's class.
(c) all original classes with x or y attached removed (classes removed) (except the last one as mentioned in (b) above)
(d) All other attributes (id and data- etc.) to stay with the div they were assigned.

So:

Code:
<div id="id1" data-test="1" class="box class1 x">
AAA
</div>
<div id="id2" data-test="2" class="box class2 x">
BBB
</div>
<div id="id3" data-test="3" class="box class3">
CCC
</div>
<div id="id4" data-test="4" class="box class4 y">
DDD
</div>
<div id="id5" data-test="5" class="box class5 y ">
EEE
</div>
..becomes:


Code:
<div class="box class2 x">

  <div id="id1" data-test="1">
  AAA
  </div>
  <div id="id2" data-test="2">
  BBB
  </div>

</div>

<div id="id3" data-test="3" class="box class3">
CCC
</div>

<div class="box class5 y">

  <div id="id4" data-test="4">
  DDD
  </div>
  <div id="id5" data-test="5">
  EEE
  </div>

</div>