TransWikia.com

Sort DOM elements based on the sorting of the array elements

Stack Overflow Asked by Proseller on January 25, 2021

I have 3 HTML elements and an array with 3 elements.

const args = ['Red', 'Purple', 'Green'];
.box {
  width: 100%;
  height: 100px;  
  color: #fff;
  border: 1px solid #fff;
  padding: 10px;
}

.green {
  background: green;
}

.red {
  background: red;
}

.purple {
  background: rebeccapurple;
}
<div class="box green">1</div>
<div class="box red">2</div>
<div class="box purple">3</div>

I would like to sort the HTML elements in DOM, based on the index of the elements in the array. So for instance, if the array is ['Red', 'Purple', 'Green'], the red box should be on top, purple in the middle and the green box in the bottom. How can I do this?

2 Answers

Like this:

const container = document.getElementById("container");
['Red', 'Purple', 'Green']
.forEach(col => 
  container.appendChild(container.querySelector("." + col.toLowerCase())))
.box {
  width: 100%;
  height: 100px;
  color: #fff;
  border: 1px solid #fff;
  padding: 10px;
}

.green {
  background: green;
}

.red {
  background: red;
}

.purple {
  background: rebeccapurple;
}
<div id="container">
  <div class="box green">1</div>
  <div class="box red">2</div>
  <div class="box purple">3</div>
</div>

If more than one div with the same class

const container = document.getElementById("container");
['Red', 'Purple', 'Green']
.forEach(col =>
  container.querySelectorAll("." + col.toLowerCase())
  .forEach(div => container.appendChild(div)))
.box {
  width: 100%;
  height: 100px;
  color: #fff;
  border: 1px solid #fff;
  padding: 10px;
}

.green {
  background: green;
}

.red {
  background: red;
}

.purple {
  background: rebeccapurple;
}
<div id="container">
  <div class="box green">1</div>
  <div class="box red">2</div>
  <div class="box purple">3</div>
  <div class="box red">4</div>
</div>

Correct answer by mplungjan on January 25, 2021

const args = ['Red', 'Purple', 'Green'].map(arg => arg.toLowerCase());

let divs = document.querySelectorAll('div.box');

let sortedDivs = Array.from(divs).sort((a, b) => {
  aClass = Array.from(a.classList).filter(clas => args.indexOf(clas) > -1)[0];
  bClass = Array.from(b.classList).filter(clas => args.indexOf(clas) > -1)[0];
  return args.indexOf(aClass) - args.indexOf(bClass);
});

sortedDivs.forEach(div => {
  document.body.appendChild(div);
});
.box {
  width: 100%;
  height: 100px;
  color: #fff;
  border: 1px solid #fff;
  padding: 10px;
}

.green {
  background: green;
}

.red {
  background: red;
}

.purple {
  background: rebeccapurple;
}
<div id="container">
  <div class="box green">1</div>
  <div class="box red">2</div>
  <div class="box purple">3</div>
  <div class="box red">4</div>
</div>

Answered by willystyle on January 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP