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
You should loop in each
main
element, and then do the insert operation for sub-mains of thatmain
element.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:
Working snippet: