Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to sort element by numerical value of data attribute using JavaScript?
In JavaScript, you can sort DOM elements by their data attributes using different approaches. This is useful when you need to reorder elements based on numerical values stored in data attributes.
This article demonstrates two methods to sort elements by numerical data attribute values:
Using the getAttribute() method to access data attributes
Using the dataset property for cleaner syntax
Using the getAttribute() Method
The getAttribute() method retrieves the value of any HTML attribute, including data attributes. This method works across all browsers and provides explicit attribute access.
Syntax
element.getAttribute("data-attributename");
Example
Here's a complete example that creates sortable elements and sorts them by data-percentage values:
<!DOCTYPE html>
<html>
<head>
<style>
.container { margin: 20px 0; }
.child-item {
padding: 10px;
margin: 5px;
background: #f0f0f0;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<h2>Sort Elements by Data Attribute</h2>
<input type="number" id="percentageInput" placeholder="Enter percentage">
<button onclick="addElement()">Add Element</button>
<button onclick="sortElements()">Sort by Percentage</button>
<div id="container" class="container"></div>
<script>
function addElement() {
const input = document.getElementById('percentageInput');
const value = parseInt(input.value);
if (isNaN(value)) {
alert('Please enter a valid number');
return;
}
const container = document.getElementById('container');
const newElement = document.createElement('div');
newElement.className = 'child-item';
newElement.textContent = `Element with ${value}%`;
newElement.setAttribute('data-percentage', value);
container.appendChild(newElement);
input.value = '';
}
function sortElements() {
const container = document.getElementById('container');
const elements = Array.from(container.children);
elements.sort((a, b) => {
const aValue = parseInt(a.getAttribute('data-percentage'));
const bValue = parseInt(b.getAttribute('data-percentage'));
return aValue - bValue; // Ascending order
});
// Re-append sorted elements
elements.forEach(element => container.appendChild(element));
}
</script>
</body>
</html>
Using the dataset Property
The dataset property provides a more modern and convenient way to access data attributes. It automatically converts kebab-case attributes to camelCase properties.
Syntax
element.dataset.attributename; // for data-attributename
Example
The same functionality using the dataset property:
<!DOCTYPE html>
<html>
<head>
<style>
.container { margin: 20px 0; }
.child-item {
padding: 10px;
margin: 5px;
background: #e8f4f8;
border: 1px solid #4CAF50;
}
</style>
</head>
<body>
<h2>Sort Elements using Dataset Property</h2>
<input type="number" id="scoreInput" placeholder="Enter score">
<button onclick="addElement()">Add Element</button>
<button onclick="sortByDataset()">Sort by Score</button>
<div id="container" class="container"></div>
<script>
function addElement() {
const input = document.getElementById('scoreInput');
const score = parseInt(input.value);
if (isNaN(score)) {
alert('Please enter a valid number');
return;
}
const container = document.getElementById('container');
const newElement = document.createElement('div');
newElement.className = 'child-item';
newElement.textContent = `Score: ${score}`;
newElement.dataset.score = score; // Using dataset property to set
container.appendChild(newElement);
input.value = '';
}
function sortByDataset() {
const container = document.getElementById('container');
const elements = Array.from(container.children);
elements.sort((a, b) => {
return parseInt(a.dataset.score) - parseInt(b.dataset.score);
});
// Clear and re-append sorted elements
container.innerHTML = '';
elements.forEach(element => container.appendChild(element));
}
</script>
</body>
</html>
Comparison
| Method | Syntax | Browser Support | Performance |
|---|---|---|---|
getAttribute() |
element.getAttribute('data-name') |
All browsers | Good |
dataset |
element.dataset.name |
Modern browsers | Better (cached) |
Key Points
Always convert data attribute values to numbers using
parseInt()orNumber()for numerical sortingUse
Array.from()to convert NodeList to Array for sorting methodsThe
datasetproperty is more readable and modernBoth methods work for ascending and descending sorts by reversing the comparison
Conclusion
Both getAttribute() and dataset methods effectively sort elements by data attributes. Choose dataset for modern applications and getAttribute() for broader browser compatibility.
