forked from lsvekis/JavaScript-Exercises-Book
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamic Table Sorting
More file actions
58 lines (58 loc) · 1.28 KB
/
Copy pathDynamic Table Sorting
File metadata and controls
58 lines (58 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<!-- Objective: Develop a dynamic table sorting feature. -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dynamic Table Sorting</title>
</head>
<body>
<table id="sortableTable">
<thead>
<tr>
<th data-type="number">ID</th>
<th data-type="text">Name</th>
<th data-type="number">Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Alice</td>
<td>30</td>
</tr>
<tr>
<td>2</td>
<td>Bob</td>
<td>24</td>
</tr>
<tr>
<td>3</td>
<td>Charlie</td>
<td>29</td>
</tr>
<!-- More rows as needed -->
</tbody>
</table>
<script>
document.querySelectorAll('#sortableTable th').forEach(header => {
header.addEventListener('click', () => {
const table = header.parentNode.parentNode.parentNode;
const tbody = table.querySelector('tbody');
const index = Array.prototype.indexOf.call(header.parentNode.children, header);
const type = header.getAttribute('data-type');
const rows = Array.from(tbody.querySelectorAll('tr'));
const sortedRows = rows.sort((a, b) => {
const aValue = a.children[index].textContent;
const bValue = b.children[index].textContent;
if (type === 'number') {
return parseFloat(aValue) - parseFloat(bValue);
} else {
return aValue.localeCompare(bValue);
}
});
sortedRows.forEach(row => tbody.appendChild(row));
});
});
</script>
</body>
</html>