Changing order of HTML elements using jQuery

Changing order of HTML elements using jQuery

If you want to change the order of HTML elements displayed on the page, there are at least two options – the first one is to try CSS display property, namely any of the table-column-group, table-header-group and other values that make HTML elements to behave as table elements. This can perform only basic tasks, though, and normally is useful inside the same HTML container only.

For any advanced change of order, jQuery is a way to go. Specifically, the insertAfter() method. Let me give you a working example:

jQuery(document).ready(function($){

if ($(window).width() < 781) {
   $("#pgc-7-0-0").insertAfter("#pgc-7-0-1");
   $("#pgc-7-1-0").insertAfter("#pgc-7-0-0");
   $("#pgc-7-0-2").insertAfter("#pgc-7-1-0");
}
else {
   //do nothing
}
});

This comes from one of the WordPress websites I’ve worked on – the request was to stack elements differently when on mobile layout (the theme was coded to go into mobile below 781px, hence the condition). Elements were not within the same container, but “scattered”all across the page.

Let’s examine the first line:

$("#pgc-7-0-0").insertAfter("#pgc-7-0-1");

The insertAfter() method is quite self-explanatory, so in this case the HTML element with #pgc-7-0-0 ID will appear after #pgc-7-0-1, regardless on the previous position within the page.

References:

.insertAfter() method
CSS display property