I understand that the wording of the question is incorrect (if someone can write it correctly, please). The task is this, I have 30 elements on the page and I need to sort them with the resulting array. That is, I get an array - let order = [2, 5, 3, 6, 12 ...]
and sorting should take place in accordance with this order, that is, the first element is the 2nd element from HTML, the second element is the 5th element from HTML (according to the given array). The initial order is equal to the number in data-custom-sort
.
There will be many such an array. And I don't understand how to do it universally. Can someone have any ideas?
I have not formulated very well, so if you have questions - ask.
The HTML is something like this:
<a id="sort-best" class="choose-cat">best</a>
<div>
<article data-custom-sort="1">
...
</article>
<article data-custom-sort="2">
...
</article>
<article data-custom-sort="3">
...
</article>
//and etc
</div>
These are product cards in the catalog. I need to sort them
document.querySelector('#sort-best').onclick = sortBest;
function sortBest() {
let nav = document.querySelector('#game-items-cart');
for (let i = 0; i < nav.children.length; i++) {
for (let j = i; j < nav.children.length; j++) {
if (+nav.children[i].getAttribute('data-sort') > +nav.children[j].getAttribute('data-sort')) {
replaceNode = nav.replaceChild(nav.children[j], nav.children[i]);
insertAfter(replaceNode, nav.children[i]);
}
}
}
}
function insertAfter(elem, refElem) {
return refElem.parentNode.insertBefore(elem, refElem.nextSibling);
}
I used this code to sort through the data
attributes. That is, the number in the data attribute = the ordinal after sorting.