element insertAfter for each instance of class

element insertAfter for each instance of class

Hi,

I have a series of divs all with the same class. Within each div, are two sub-element divs. With the use of a function I would like to swap round the order of these two sub divs, so the first sub div comes after the second.

This is the HTML:

  1. <div class="containingDiv">
  2. <div id="first_sub_div">first div copy</div>
  3. <div id="second_sub_div"">second div copy</div>
  4. </div>



Both this:

  1. function myFunction() {
  2.          jQuery(".containingDiv").find("#first_sub_div").insertAfter(jQuery(".containingDiv").find("#first_sub_div").next());
  3. }

and this:


  1. function myFunction() {
  2.  jQuery(".containingDiv").each(
  3.     function(){
  4.       jQuery(this).find("#first_sub_div").insertAfter(jQuery(this).find("#first_sub_div").next());;
  5.     
  6.     }
  7. }

loop through all of the first_sub_divs, and place them after the second_sub_div (i.e. if they are 10 instances of the class containingDiv, then each second_sub_div has x10 first_sub_divs after it, when I only want to swap round the one directly before it for each case.

Can clarify further if needed. Pretty such I don't need the for each function as using a class means Jquery iterates over all the instances of it anyway, but don't know how to do this properly.