I've been twisting my brain over this for a while now: I need to get a jQuery function to move each instance of .THIS
after the first-following .THAT
. I broke it down to this simple HTML example:
<table><tr>
<td class="1a">1a</td>
<td class="2a">2a</td>
<td class="3a THIS">3a</td>
<td class="4a">4a</td>
<td class="5a THAT">5a</td>
</tr>
<tr>
<td class="1a THIS">1a</td>
<td class="2a">2a</td>
<td class="3a">3a</td>
<td class="4a THAT">4a</td>
<td class="5a">5a</td>
</tr></table>
And I figured this would work
var source = jQuery('.THIS');
var destination = jQuery(source).nextAll('.THAT');
jQuery(source).insertAfter(destination);
But whenever I try this, both sources (.THIS
) get moved after the last instance of .THAT
, like so:
<table><tr>
<td class="1a">1a</td>
<td class="2a">2a</td>
<td class="4a">4a</td>
<td class="5a THAT">5a</td>
</tr>
<tr>
<td class="2a">2a</td>
<td class="3a">3a</td>
<td class="4a THAT">4a</td>
<td class="3a THIS">3a</td>
<td class="1a THIS">1a</td>
<td class="5a">5a</td>
</tr></table>
Instead of this:
<table><tr>
<td class="1a">1a</td>
<td class="2a">2a</td>
<td class="4a">4a</td>
<td class="5a THAT">5a</td>
<td class="3a THIS">3a</td>
</tr>
<tr>
<td class="2a">2a</td>
<td class="3a">3a</td>
<td class="4a THAT">4a</td>
<td class="1a THIS">1a</td>
<td class="5a">5a</td>
</tr></table>
So how can I use jQuery to move each instance after the first other one?
You need to tackle each .THIS
individually, and place it after the first entry in nextAll()
's results.
var source = jQuery('.THIS');
source.each(
function() {
var $this = jQuery(this);
$this.insertAfter( $this.nextAll('.THAT')[0] );
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td class="1a">1a</td>
<td class="2a">2a</td>
<td class="3a THIS">3a</td>
<td class="4a">4a</td>
<td class="5a THAT">5a</td>
</tr>
<tr>
<td class="1a THIS">1a</td>
<td class="2a">2a</td>
<td class="3a">3a</td>
<td class="4a THAT">4a</td>
<td class="5a">5a</td>
</tr>
</table>