-2

I have this bit of HTML code.

<div class="container">

 <div class="single-result">
  <span class="flight-no">VL2100</span>
  <span class="cabin">Economy</span>
  <span class="price">35000</span>
 </div>

 <div class="single-result">
  <span class="flight-no">VL2101</span>
  <span class="cabin">Economy</span>
  <span class="price">40000</span>
 </div>

 <div class="single-result">
  <span class="flight-no">VL2100</span>
  <span class="cabin">Economy</span>
  <span class="price">22000</span>
 </div>

 <div class="single-result">
  <span class="flight-no">VL2100</span>
  <span class="cabin">Economy</span>
  <span class="price">14500</span>
 </div>

</div>

How do I sort it -- based on price -- using Javascript? Please, don't ask me for my JS code. My only thought was to use the bubble sort algorithm. But then, bubble sort works only on sorted arrays and my HTML string isn't sorted. Any suggestions, pointers and / or code will be appreciated.

Community
  • 1
  • 1
NaijaProgrammer
  • 2,892
  • 2
  • 24
  • 33

1 Answers1

2

Create an array and insert for each element 2 fields, the HTML element and the price, sort the array, re-insert the elements after sorting to conainer after make it empty:

var elements = document.querySelectorAll('.single-result');

var sortable = [];
for (i=0;i<elements.length;i++){
  sortable.push([elements[i], elements[i].querySelector('.price').textContent]);
}

sortable.sort(function(a, b) {return a[1] - b[1]});

container = document.querySelector('.container');
container.innerHTML = "";

sortable.forEach(function(item) {
  container.appendChild(item[0]);
});
mohamed-ibrahim
  • 10,837
  • 4
  • 39
  • 51