You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

按内容日期对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 the NodeList (returned by querySelectorAll) into a proper array—this lets us use the built-in sort() method.
  • Date Parsing: The date format 04 Apr 2018 is natively supported by the Date constructor, so parsing it is straightforward. If you ever work with non-standard date formats, you'll need to split the string and manually construct the Date object (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 a while loop to remove existing children one by one. This keeps any event bindings intact.
  • Flexible Order: The function accepts an ascending parameter 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:17:20