Zoradenie elementov v JavaScripte / sort function

<div class="produkt">2</div>
<div class="produkt">1</div>
<div class="produkt">3</div>
<button id="zorad">Zoraď</button>
  function zoradProdukty() {
           var items = document.querySelectorAll('.produkt');   // definuj elementy
           // magically coerce into an array first
           items = Array.prototype.slice.call(items);
           // Now we can sort it.  Sort alphabetically
           items.sort(function(a, b){
               return b.textContent.localeCompare(a.textContent);   // vymenit a b pre opacne zoradenie
           });
           // reatach the sorted elements
           for(var i = 0, len = items.length; i < len; i++) {
               // store the parent node so we can reatach the item
               var parent = items[i].parentNode;
               // detach it from wherever it is in the DOM
               var detatchedItem = parent.removeChild(items[i]);
               parent.appendChild(detatchedItem);
           }
           window.scrollTo(0, 0);
        }
   document.getElementById('zorad').addEventListener('click', zoradProdukty)

Pridaj komentár

Vaša e-mailová adresa nebude zverejnená.