Sort HTML elements by data-attribute [duplicate]

  • A+
Category:Languages

This question already has an answer here:

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

 


You can (and should) use Array#sort, just pass it a function that checks the data-category-group property:

var categoryItems = document.querySelectorAll("[data-category-group]"); var categoryItemsArray = Array.from(categoryItems);  let sorted = categoryItemsArray.sort(sorter);  function sorter(a,b) {     if(a.dataset.categoryGroup < b.dataset.categoryGroup) return -1;     if(a.dataset.categoryGroup > b.dataset.categoryGroup) return 1; }  document.querySelector("button").onclick = () => sorted.forEach(e => document.querySelector("#demo").appendChild(e));
<ul id="demo">   <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>   <button>Sort Elements</button>

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: