-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.

6
  • sort the elements based on what Commented Apr 27, 2015 at 10:51
  • Why can't we see your code? Commented Apr 27, 2015 at 10:51
  • @ArunPJohny I assume they mean .single-result Commented Apr 27, 2015 at 10:51
  • 1
    stackoverflow.com/questions/14131008/… Commented Apr 27, 2015 at 10:53
  • 3
    Pretty straight forward really -> jsfiddle.net/adeneo/p0Lkw81j Commented Apr 27, 2015 at 10:57

1 Answer 1

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]);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.