I have the following markup:
<ul>
<li class="category-item" data-category-group="jeans">Bottoms</li>
<li class="category-item" data-category-group="tops">Shirt</li>
<li class="category-item" data-category-group="jeans">Jeans</li>
<li class="category-item" data-category-group="jeans">Shorts</li>
<li class="category-item" data-category-group="tops">Hoodie</li>
<li class="category-item" data-category-group="accesories">Sunglasses</li>
</ul>
The elements can have different group names in the data-category-group
attribute. I want to be able to sort the elements so that the elements with the group of jeans will all come after each other in the DOM.
I had an idea to try to solve this by turning the HTML collection into an array and then sort them. But its does not seem to be able to work that way.
Here is my JavaScript:
var categoryItems = document.querySelectorAll("[data-category-group]");
var categoryItemsArray = Array.from(categoryItems)
document.getElementById("demo").innerHTML = categoryItemsArray;
function myFunction() {
categoryItemsArray.sort();
document.getElementById("demo").innerHTML = categoryItemsArray;
}
How could this be achieved?
Checkout a codepen here: https://codepen.io/fennefoss/pen/PBGrPZ