D
D
devilwish2020-05-04 18:48:58
JavaScript
devilwish, 2020-05-04 18:48:58

Why doesn't sorting work?

$(document).ready(function(){
document.querySelector('.increase').onclick = inCrease;
document.querySelector('.decrease').onclick = deCrease;
function inCrease(){
  let products = document.querySelector('.sorting');
  console.log(products);
  for (let i = 0; i < products.children.length; i++){
    for (let j = i; j < products.children.length; j++){
      if (+products.children[i].getAttribute('data-sort') > +products.children[j].getAttribute('data-sort')){
         replacedNode = products.replaceChild(products.children[j], products.children[i]);
         insertAfter(replacedNode, products.children[i]);
      }

    }
  }
}
function deCrease(){
  let products = document.querySelector('.sorting');
  console.log(products);
  for (let i = 0; i < products.children.length; i++){
    for (let j = i; j < products.children.length; j++){
      if (+products.children[i].getAttribute('data-sort') < +products.children[j].getAttribute('data-sort')){
         replacedNode = products.replaceChild(products.children[j], products.children[i]);
         insertAfter(replacedNode, products.children[i]);
      }

    }
  }
}

function insertAfter(elem, refElem){
  return refElem.parentNode.insertBefore(elem, refElem.nextSibiling);
}
});
            </script>

I wrote the following sorting in ascending and descending prices, assigned the sorting class to 5 divs by elements (data-sort), but the sorting works only in the first div. Why?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2020-05-04
@Rsa97

Because querySelector only returns the first element that matches the selector.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question