Member-only story
How to Use JavaScript to Rearrange Elements on a Web Page
Sort divs based on contents
Have you ever been to a web page that has content not sorted the way you would like? And it doesn’t have a feature to sort it out?
It can be really frustrating, but luckily, if you really need to have the content sorted, you can easily do it yourself using JavaScript!
In this tutorial, I’ll guide you step by step with an example from DEV:
Tutorial
Open the page you want to sort in your browser, open the DevTools (F12
) and be ready to explore the DOM structure of your page!
1 . Determine the structure of an element
In order to be able to sort all the items, you must understand how an element that you want to be sorted is made. Select the element with the Inspect button (or Ctrl + Shift + C
) and expand it recursively.
2. Determine what the elements will be sorted on
Do you want to sort the divs by their title? Maybe by a numeric attribute?
In my case, I want to sort them by the number of posts published. If I type $0.querySelector('p.color-base-60').innerText
in the console, I'm able to obtain 64765 posts published
.
3 . Determine the order
Do you want an ascending order or a descending order?
const ascendingOrder = false;
4. Select all the elements
Are you able to find a selector to get all the items you want to sort? In my case, all the elements have the tag-card
class.
const elements = [...document.querySelectorAll('.tag-card')];