Sort Elements Based on Data Attributes with Vanilla JavaScript

In a recent project, I was tasked with sorting a large list of elements dynamically based on multiple data attributes. Below, I’ll show you how to achieve this using just data attributes and vanilla JavaScript.

How It Works

  • Sorting Function: The sortListBy function takes two parameters: attribute (the data attribute you want to sort by, such as “price” or “score”) and order (either 'asc' for ascending or 'desc' for descending).
    • It first selects the list and its items.
    • Then, it sorts the items based on the value of the specified attribute, using parseInt to convert the attribute values to numbers.
    • Finally, it appends the sorted items back to the list in the correct order.
  • Event Listeners: Each link (.sort1, .sort2, .sort3, .sort4) has an event listener attached to it that triggers the sorting function with the appropriate attribute and order when clicked.

Creating the List

First, we need a simple unordered list (<ul>) where each list item has custom data attributes. These data attributes can hold numerical values that we will use for sorting.

<ul class="sort-list">
    <li data-score="1" data-price="123">€ 123 (Score: 1)</li>
    <li data-score="5" data-price="67">€ 67 (Score: 2)</li>
    <li data-score="4" data-price="111">€ 111 (Score: 3)</li>
    <li data-score="3" data-price="4">€ 4 (Score: 4)</li>
    <li data-score="2" data-price="200">€ 200 (Score: 5)</li>
</ul>

Next, we create buttons or links to trigger the sorting by either the data-price or data-score attributes. These will allow the user to sort the list based on different criteria.

<a href="#" class="sort1">Sort by price (descending)</a> 
<a href="#" class="sort2">Sort by price (ascending)</a> 
<a href="#" class="sort3">Sort by score (descending)</a> 
<a href="#" class="sort4">Sort by score (ascending)</a>

Writing the Sorting Function

Now we need to write the sorting function in vanilla JavaScript. This function will handle sorting by a specified data attribute, either in ascending or descending order.

// Function to sort the list based on a specific data attribute and order
function sortListBy(attribute, order) {
  const list = document.querySelector('ul.sort-list');
  const items = Array.from(list.children); // Convert the NodeList to an array

  // Sort the list items based on the specified attribute
  items.sort((a, b) => {
    const aValue = parseInt(a.getAttribute(`data-${attribute}`), 10);
    const bValue = parseInt(b.getAttribute(`data-${attribute}`), 10);

    if (order === 'asc') {
      return aValue - bValue;
    } else {
      return bValue - aValue;
    }
  });

  // Reorder the list items
  items.forEach(item => list.appendChild(item));
}

Setting Up the Event Listeners

Now, we need to add event listeners to the sorting links so that when the user clicks on one of them, the sorting function is triggered accordingly.

// Event listeners for sorting actions
document.querySelector('.sort1').addEventListener('click', function(e) {
  e.preventDefault(); // Prevent default link behavior
  sortListBy('price', 'desc'); // Sort by price in descending order
});

document.querySelector('.sort2').addEventListener('click', function(e) {
  e.preventDefault();
  sortListBy('price', 'asc'); // Sort by price in ascending order
});

document.querySelector('.sort3').addEventListener('click', function(e) {
  e.preventDefault();
  sortListBy('score', 'desc'); // Sort by score in descending order
});

document.querySelector('.sort4').addEventListener('click', function(e) {
  e.preventDefault();
  sortListBy('score', 'asc'); // Sort by score in ascending order
});

See our demo on Codepen!

on in JavaScript Arrays & Objects | Last modified on

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *