Changing order of HTML elements using jQuery

Home / 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-grouptable-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:

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:

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.