How to change order of divs with jQuery?

Sometimes, we want to change order of divs with jQuery

In this article, we’ll look at how to change order of divs with jQuery.

How to change order of divs with jQuery?

To change order of divs with jQuery, we can use the insertAfter method.

For instance, we write:

<div class="test one">aaa</div>
<div class="test two">bbb</div>
<div class="test three">ccc</div>

to add 3 divs.

Then we take the first div and insert it after the 3rd with:

const tests = $('.test');
tests.first().insertAfter(tests.last());

We select all 3 divs with class test with $('.test').

Then we get the first of the elements with first.

And we call insertAfter with the element to insert the first element after.

We called it with tests.last() so we insert the first element after the last element.

Therefore, we see:

bbb
ccc
aaa

displayed.

Conclusion

To change order of divs with jQuery, we can use the insertAfter method.