forked from lsvekis/JavaScript-Exercises-Book
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamic List Sorting
More file actions
38 lines (38 loc) · 1.13 KB
/
Dynamic List Sorting
File metadata and controls
38 lines (38 loc) · 1.13 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
<!-- Objective: Implement dynamic list sorting functionality. -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dynamic List Sorting</title>
</head>
<body>
<select id="sortCriteria">
<option value="ascending">A to Z</option>
<option value="descending">Z to A</option>
<!-- Add more sort criteria as needed -->
</select>
<ul id="itemList">
<li>Orange</li>
<li>Apple</li>
<li>Mango</li>
<li>Banana</li>
</ul>
<script>
const sortCriteria = document.getElementById('sortCriteria');
const itemList = document.getElementById('itemList');
function sortList(criteria) {
let itemsArray = Array.from(itemList.getElementsByTagName('li'));
itemsArray.sort((a, b) => {
const textA = a.textContent.toUpperCase(); // Case-insensitive
const textB = b.textContent.toUpperCase(); // Case-insensitive
return criteria === 'ascending' ? textA.localeCompare(textB) : textB.localeCompare(textA);
});
while (itemList.firstChild) {
itemList.removeChild(itemList.firstChild);
}
itemsArray.forEach(item => itemList.appendChild(item));
}
sortCriteria.addEventListener('change', () => sortList(sortCriteria.value));
</script>
</body>
</html>