skip to Main Content

I have an HTML structure like this:

<div class="main">
    <div class="sub-main1">Content</div>
    <div class="sub-main2">Content</div>
</div>
<div class="main">
    <div class="sub-main1">Content</div>
    <div class="sub-main2">Content</div>
</div>

Now, I want to move sub-main2 above sub-main1. And I have used this script:

jQuery( ".sub-main2" ).insertBefore( jQuery( ".sub-main1" ) );

Now, each div with class main has 2 divs with class sub-main2.

Can someone please help me with where I am making the mistake?

Thanks.

2

Answers


  1. You should loop in each main element, and then do the insert operation for sub-mains of that main element.

          jQuery('.main').each(function () {
            var subMain1 = jQuery(this).find('.sub-main1');
            var subMain2 = jQuery(this).find('.sub-main2');
            subMain2.insertBefore(subMain1);
          });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="main">
        <div class="sub-main1">main 1 Content 1</div>
        <div class="sub-main2">main 1 Content 2</div>
      </div>
      <div class="main">
        <div class="sub-main1">main 2 Content 1</div>
        <div class="sub-main2">main 2 Content 2</div>
      </div>
    Login or Signup to reply.
  2. Your code is selecting all .sub-main2 elements and places them before all of .sub-main1 elements. That’s why you get repeated once.

    You need to apply a loop where you can find individual .sub-main2 to place before the corresponding .sub-main1 one.

    Do it like this:

    $('.sub-main2').each(function() { $(this).insertBefore($(this).prev()); });
    

    Working snippet:

    $('.sub-main2').each(function() { $(this).insertBefore($(this).prev()); });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="main">
        <div class="sub-main1">Content1-1</div>
        <div class="sub-main2">Content1-2</div>
    </div>
    <div class="main">
        <div class="sub-main1">Content2-1</div>
        <div class="sub-main2">Content2-2</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search