How to sort HTML elements by data-attribute?

In HTML, you can sort elements by their data attributes using JavaScript. Data attributes allow you to store custom information directly in HTML elements, which can then be used for sorting, filtering, or other dynamic operations. This technique is particularly useful when you need to reorder elements based on custom criteria without modifying the original HTML structure.

Common use cases include sorting product lists by price, organizing content by date, or arranging elements by priority levels stored in data attributes.

Syntax

Following is the basic syntax for adding data attributes to HTML elements

<div data-attribute="value">Content</div>

To access data attributes in JavaScript, use the dataset property

element.dataset.attribute

Using data-index Attribute for Numeric Sorting

The data-index attribute stores numeric values that can be used to sort elements in ascending or descending order. This method is ideal for sorting by priority, sequence numbers, or any numerical criteria.

Example

Following example demonstrates sorting HTML elements by numeric data-index values

<!DOCTYPE html>
<html>
<head>
   <title>Sort by data-index</title>
   <style>
      .container { margin: 20px 0; }
      .item { 
         padding: 10px; 
         margin: 5px 0; 
         background: #f0f8ff; 
         border: 1px solid #ddd; 
         border-radius: 4px; 
      }
      button { 
         padding: 8px 16px; 
         margin: 5px; 
         background: #007bff; 
         color: white; 
         border: none; 
         border-radius: 4px; 
         cursor: pointer; 
      }
   </style>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Sort Elements by data-index Attribute</h2>
   
   <input type="number" id="numberInput" placeholder="Enter a number" style="padding: 8px; margin: 5px;">
   <button onclick="addElement()">Add Element</button>
   <button onclick="sortElements()">Sort by Index</button>
   
   <div id="container" class="container"></div>
   
   <script>
      function addElement() {
         const input = document.getElementById('numberInput');
         const value = parseInt(input.value);
         
         if (!isNaN(value)) {
            const container = document.getElementById('container');
            const newElement = document.createElement('div');
            newElement.className = 'item';
            newElement.setAttribute('data-index', value);
            newElement.textContent = `Element with index: ${value}`;
            container.appendChild(newElement);
            input.value = '';
         }
      }
      
      function sortElements() {
         const container = document.getElementById('container');
         const items = Array.from(container.children);
         
         items.sort((a, b) => {
            const indexA = parseInt(a.dataset.index);
            const indexB = parseInt(b.dataset.index);
            return indexA - indexB;
         });
         
         // Re-append sorted elements
         items.forEach(item => container.appendChild(item));
      }
   </script>
</body>
</html>

The output allows you to add numbered elements and sort them in ascending order

[Input field] [Add Element] [Sort by Index]

Element with index: 5
Element with index: 1  
Element with index: 3

(After clicking "Sort by Index"):
Element with index: 1
Element with index: 3
Element with index: 5

Using data-subject Attribute for String Length Sorting

The data-subject attribute can store string values, and elements can be sorted based on the length of these strings. This is useful for organizing content by text length, complexity, or alphabetical criteria.

Example

Following example shows sorting elements based on the length of data-subject values

<!DOCTYPE html>
<html>
<head>
   <title>Sort by data-subject Length</title>
   <style>
      .container { margin: 20px 0; }
      .subject-item { 
         padding: 12px; 
         margin: 5px 0; 
         background: #f5f5f5; 
         border: 1px solid #ccc; 
         border-radius: 4px; 
      }
      .subject-name { font-weight: bold; color: #333; }
      .topic-name { color: #666; margin-left: 10px; }
      button { 
         padding: 8px 16px; 
         margin: 5px; 
         background: #28a745; 
         color: white; 
         border: none; 
         border-radius: 4px; 
         cursor: pointer; 
      }
   </style>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Sort Elements by data-subject Length</h2>
   
   <input type="text" id="subjectInput" placeholder="Subject name" style="padding: 8px; margin: 5px;">
   <input type="text" id="topicInput" placeholder="Topic name" style="padding: 8px; margin: 5px;">
   <button onclick="addSubject()">Add Subject</button>
   <button onclick="sortByLength()">Sort by Subject Length</button>
   
   <div id="subjectContainer" class="container"></div>
   
   <script>
      function addSubject() {
         const subjectInput = document.getElementById('subjectInput');
         const topicInput = document.getElementById('topicInput');
         const subject = subjectInput.value.trim();
         const topic = topicInput.value.trim();
         
         if (subject && topic) {
            const container = document.getElementById('subjectContainer');
            const newElement = document.createElement('div');
            newElement.className = 'subject-item';
            newElement.setAttribute('data-subject', subject);
            newElement.innerHTML = `<span class="subject-name">${subject}</span><span class="topic-name">: ${topic}</span>`;
            container.appendChild(newElement);
            
            subjectInput.value = '';
            topicInput.value = '';
         }
      }
      
      function sortByLength() {
         const container = document.getElementById('subjectContainer');
         const items = Array.from(container.children);
         
         items.sort((a, b) => {
            const lengthA = a.dataset.subject.length;
            const lengthB = b.dataset.subject.length;
            return lengthA - lengthB; // Sort by ascending length
         });
         
         // Re-append sorted elements
         items.forEach(item => container.appendChild(item));
      }
   </script>
</body>
</html>

The output displays subjects sorted by the length of their names

[Subject input] [Topic input] [Add Subject] [Sort by Subject Length]

Math: Algebra
JavaScript: DOM Manipulation  
CSS: Styling

(After sorting by length):
CSS: Styling
Math: Algebra
JavaScript: DOM Manipulation

Advanced Sorting with Multiple Data Attributes

You can sort elements using multiple data attributes for more complex sorting logic. The following example combines numeric and string sorting

Example

<!DOCTYPE html>
<html>
<head>
   <title>Multi-Attribute Sorting</title>
   <style>
      .product { 
         padding: 15px; 
         margin: 8px 0; 
         background: #fff5f5; 
         border: 1px solid #e0e0e0; 
         border-radius: 6px; 
      }
      .price { font-weight: bold; color: #d63384; }
      .rating { color: #ff8c00; }
      button { 
         padding: 10px 15px; 
         margin: 5px; 
         border: none; 
         border-radius: 4px; 
         cursor: pointer; 
         color: white; 
      }
      .sort-price { background: #6f42c1; }
      .sort-rating { background: #fd7e14; }
   </style>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Multi-Attribute Product Sorting</h2>
   
   <button class="sort-price" onclick="sortByPrice()">Sort by Price</button>
   <button class="sort-rating" onclick="sortByRating()">Sort by Rating</button>
   
   <div id="productContainer">
      <div class="product" data-price="299" data-rating="4.5">
         <div>Laptop Stand - <span class="price">$299</span> - <span class="rating">?4.5</span></div>
      </div>
      <div class="product" data-price="89" data-rating="3.8">
         <div>Wireless Mouse - <span class="price">$89</span> - <span class="rating">?3.8</span></div>
      </div>
      <div class="product" data-price="159" data-rating="4.9">
         <div>Mechanical Keyboard - <span class="price">$159</span> - <span class="rating">?4.9</span></div>
      </div>
   </div>
   
   <script>
      function sortByPrice() {
         const container = document.getElementById('productContainer');
         const products = Array.from(container.children);
         
         products.sort((a, b) => {
            return parseInt(a.dataset.price) - parseInt(b.dataset.price);
         });
         
         products.forEach(product => container.appendChild(product));
      }
      
      function sortByRating() {
         const container = document.getElementById('productContainer');
         const products = Array.from(container.children);
         
         products.sort((a, b) => {
            return parseFloat(b.dataset.rating) - parseFloat(a.dataset.rating); // Descending
         });
         
         products.forEach(product => container.appendChild(product));
      }
   </script>
</body>
</html>

The output allows sorting the same products by different criteria

[Sort by Price] [Sort by Rating]

Laptop Stand - $299 - ?4.5
Wireless Mouse - $89 - ?3.8  
Mechanical Keyboard - $159 - ?4.9

(Sort by Price - ascending):
Wireless Mouse - $89 - ?3.8
Mechanical Keyboard - $159 - ?4.9
Laptop Stand - $299 - ?4.5

(Sort by Rating - descending):
Mechanical Keyboard - $159 - ?4.9
Laptop Stand - $299 - ?4.5
Wireless Mouse - $89 - ?3.8
Sorting Process Flow 1. Select Elements Array.from() 2. Sort by Data array.sort() 3. Compare Values dataset.attribute
Updated on: 2026-03-16T21:38:54+05:30

900 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements