фильтр цены товара
Подскажите в чем ошибка, в консоле ошибки нету, но сам фильтр работает не правильно, кнопка рейтинга вообще не работае...
document.querySelector('#sort-asc').onclick = function() {
ascSort('data-price');
}
document.querySelector('#sort-desc').onclick = function() {
descSort('data-price');
}
document.querySelector('#rating').onclick = function() {
descSort('data-rating');
}
function ascSort(sortType) {
let content = document.querySelector('#content');
for (let i = 0; i < content.children.length - 1; i++) {
for (let j = 1; j < content.children.length; j++) {
if (+content.children[i].getAttribute(sortType) > +content.children[j].getAttribute(sortType)) {
let replacedNode = content.replaceChild(content.children[j], content.children[i]);
insertAfter(replacedNode, content.children[i]);
}
}
}
}
function descSort(sortType) {
let content = document.querySelector('#content');
for (let i = 0; i < content.children.length - 1; i++) {
for (let j = 1; j < content.children.length; j++) {
if (+content.children[i].getAttribute(sortType) < +content.children[j].getAttribute(sortType)) {
let replacedNode = content.replaceChild(content.children[j], content.children[i]);
insertAfter(replacedNode, content.children[i]);
}
}
}
}
function insertAfter(elem, refElem) {
return refElem.parentNode.insertBefore(elem, refElem.nextSibling);
}
Ответы (1 шт):
Автор решения: c_k_rim
→ Ссылка
Используя es6 синтаксис, функция сортировки элементов может выглядеть так:
const sortNodes = (sortType, orderType = 'asc') => {
const list = document.querySelector('#content');
[...list.children]
.sort((a, b)=> a.getAttribute(sortType) > b.getAttribute(sortType) ? 1 : -1)
.forEach(node => orderType === 'asc' ? list.appendChild(node) : list.prepend(node))
}
Так же на eng-язычном stackoverflow довольно много материала по этой ссылке: https://stackoverflow.com/questions/282670/easiest-way-to-sort-dom-nodes