How to Use JavaScript to Rearrange Elements on a Web Page | by Benjamin Rancourt | Apr, 2022

Photograph by Sarah Chai from Pexels

Have you ever ever been to an online web page that has content material not sorted the best way you want to? And it doesn’t have a characteristic to kind it out?

It may be actually irritating, however fortunately, if you really want to have the content material sorted, you may simply do it your self utilizing JavaScript!

On this tutorial, I’ll information you step-by-step with an instance from DEV:

Screenshot of the “Top tags” web page on DEV, the place the tags gave the impression to be sorted in an unknown order

Open the web page you need to kind in your browser, open the DevTools (F12) and be able to discover the DOM construction of your web page!

1 . Decide the construction of a component

So as to have the ability to kind all of the gadgets, you will need to perceive how a component that you simply need to be sorted is made. Choose the aspect with the Examine button (or Ctrl + Shift + C) and develop it recursively.

2. Decide what the weather will probably be sorted on

Do you need to kind the divs by their title? Perhaps by a numeric attribute?

In my case, I need to kind them by the variety of posts printed. If I sort $0.querySelector('p.color-base-60').innerText within the console, I can get hold of 64765 posts printed.

3 . Decide the order

Would you like an ascending order or a descending order?

const ascendingOrder = false;

4. Choose all the weather

Can you discover a selector to get all of the gadgets you need to kind? In my case, all the weather have the tag-card class.

const parts = [...document.querySelectorAll('.tag-card')];

5 . Discover the mum or dad node of all parts

You’ll be able to write one other selector to search out the div aspect that comprises all the kids, or you may select the best approach and ask the primary aspect for its mum or dad.

const parentElement = doc.querySelector('.grid');

// or

const parentElement = parts[0].parentNode;

We are going to use the mum or dad node to reorder its youngsters by preserving its construction.

6 . Type the weather

Now could be the time to assemble all of the scripts into one and run it on our web page!

The tags have now been sorted by their respective variety of printed posts!

And now, take pleasure in your new web page!

More Posts