按内容日期对Div元素排序:指定结构Div代码的排序实现需求
Solution to Sort .transitem Elements by transdate
Hey there! Let's sort those transaction items by their date values. Below is a vanilla JavaScript implementation that works seamlessly with your existing HTML structure—no frameworks required.
Step-by-Step Implementation
First, here's the complete function to handle the sorting:
function sortTransactionsByDate(ascending = true) { // Grab the parent container const transList = document.getElementById('translist'); // Convert the NodeList of .transitem elements into an array const transItems = Array.from(transList.querySelectorAll('.transitem')); // Sort the array based on the transdate value transItems.sort((itemA, itemB) => { // Extract and parse the date text from each item const dateTextA = itemA.querySelector('.transdate').textContent.trim(); const dateTextB = itemB.querySelector('.transdate').textContent.trim(); const dateA = new Date(dateTextA); const dateB = new Date(dateTextB); // Return comparison result: ascending or descending order return ascending ? dateA - dateB : dateB - dateA; }); // Clear the original container and re-add sorted items // Use this method if you need to preserve event listeners on items while (transList.firstChild) { transList.removeChild(transList.firstChild); } transItems.forEach(item => transList.appendChild(item)); } // Example triggers: // 1. Auto-sort when the page finishes loading document.addEventListener('DOMContentLoaded', () => { sortTransactionsByDate(); // Default to ascending order (oldest first) }); // 2. Or bind to a button click (if you have a button with id="sortBtn") // document.getElementById('sortBtn').addEventListener('click', () => { // sortTransactionsByDate(false); // Pass false for descending order (newest first) // });
Key Details Explained
- Array Conversion: We use
Array.from()to turn theNodeList(returned byquerySelectorAll) into a proper array—this lets us use the built-insort()method. - Date Parsing: The date format
04 Apr 2018is natively supported by theDateconstructor, so parsing it is straightforward. If you ever work with non-standard date formats, you'll need to split the string and manually construct theDateobject (e.g., mapping month names to numeric values). - Preserving Event Listeners: Instead of using
transList.innerHTML = ''(which destroys elements and loses attached event listeners), we use awhileloop to remove existing children one by one. This keeps any event bindings intact. - Flexible Order: The function accepts an
ascendingparameter to toggle between ascending (oldest first) and descending (newest first) sorting.
Edge Case Handling
If you might encounter invalid date strings, add a check to handle them gracefully (e.g., push invalid entries to the end of the list):
const dateA = new Date(dateTextA); const dateB = new Date(dateTextB); // Handle invalid dates if (isNaN(dateA.getTime())) return 1; if (isNaN(dateB.getTime())) return -1;
内容的提问来源于stack exchange,提问作者Avista Kautsar
相关产品推荐
相关产品推荐

