-1

I have this fiddle that sorts items on my webpage. I can see it works by checking the console.log results. I just don't know how to make the results appear on the actual webpage -- the items sorted in order.

http://jsfiddle.net/AQFFq/21/

function myFunction() {
var elements = [].slice.call(document.getElementsByClassName("price"));
elements.sort(function(a, b) {
return parseFloat(b.innerHTML.substring(1)) - parseFloat(a.innerHTML.substring(1));
});
for (var i = 0; i < elements.length; i++)
elements[i].parentNode.appendChild(elements[i]);
console.log(elements);
}

Thanks.

  • I know your answer is dealing with updating the DOM (the page that is actually displayed) however for your situation I might also recommend you looking into the framework angular.js it has functions that make this kind of thing simple and easy. – Binvention Dec 29 '15 at 07:45
  • I'm still confused :( – Antonio Bandana Dec 29 '15 at 11:55
  • okay upon closer inspection i found your first main problem is that you don't have {} around your for loop so its only running once. second your appending your price element to its own parent node meaning the sorting of it does absolutely nothing since the parent node of the element does not change again i would look into angular.js instead but i will help you solve this. assuming your trying to sort by price i will come up with a working solution – Binvention Dec 29 '15 at 17:03
  • another thing i noticed from your fiddle was that your products were already in the order that the sorting function sorted them in. – Binvention Dec 29 '15 at 17:14

1 Answers1

0

as i mentioned in my comments you have a couple of problems with your sorting. 1 there isnt {} around your for loop so it is only running once. 2 your are appending the price to its own parent node and since the parent nodes are still in their original order the function does nothing. what you need to do is select the parent node that is the entire element you want to sort and append that to the first parent node your sortable items have in common. here is a jsfiddle for what i mean functioning fiddle ps i switched a and b in your sort function so that the result is actually different then the original page.

Binvention
  • 1,057
  • 1
  • 8
  • 24