Categories
JavaScript Answers

How to Change the Order of HTML Elements with JavaScript?

Spread the love

Sometimes, we want to change the order of HTML elements with JavaScript.

In this article, we’ll look at how to change the order of HTML elements with JavaScript.

Change the Order of HTML Elements with JavaScript

To change the order of HTML elements with JavaScript, we can use some native JavaScript DOM manipulation functions.

For instance, if we have the following HTML:

<ul>
  <li>Dogs</li>
  <li>Snakes</li>
  <li>Cats</li>
  <li>Bugs</li>
</ul>

We can sort the li elements in alphabetical order with:

const reorder = () => {
  const frag = document.createDocumentFragment();
  const list = document.querySelector("ul");
  const items = list.querySelectorAll("li");
  const sortedList = [...items].sort((a, b) => {
    const c = a.textContent,
      d = b.textContent;
    return c < d ? -1 : c > d ? 1 : 0;
  });
  for (const item of sortedList) {
    frag.appendChild(item);
  }
  list.appendChild(frag);
}

reorder()

We create the reorder function to reorder the elements.

To do this, we create a new document fragment to hold the new content with document.createDocumentFragment .

Then we select all the li elements in the list with:

const list = document.querySelector("ul");
const items = list.querySelectorAll("li");

Next, we sort all the items by their text content value with:

const sortedList = [...items].sort((a, b) => {
  const c = a.textContent,
    d = b.textContent;
  return c < d ? -1 : c > d ? 1 : 0;
});

Then we add the sorted items into the fragment with:

for (const item of sortedList) {
  frag.appendChild(item);
}

Finally, we append the fragment into the list with:

list.appendChild(frag);

Conclusion

To change the order of HTML elements with JavaScript, we can use some native JavaScript DOM manipulation functions.

Leave a Reply

Your email address will not be published. Required fields are marked *