首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

JavaScript DOM 排序實戰:按數字 ID 重新排列 HTML 元素

     編輯:程式設計綜合問答

需求

將無序的 <div id="cd3">...</div> 等元素,按 ID 中的數字(0-9)升序重新排列到父容器中。

核心思路

  1. 獲取所有子元素到數組
  2. 提取 ID 中的數字進行排序
  3. 按排序後順序 appendChild 重新掛載(自動移動)

完整可運行代碼

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>DOM 元素排序演示</title>
    <style>
        #content > div { padding: 8px; margin: 4px 0; background: #f0f0f0; border: 1px solid #ddd; }
    </style>
</head>
<body>
    <div id="content">
        <div id="cd3">內容3</div>
        <div id="cd9">內容9</div>
        <div id="cd1">內容1</div>
        <div id="cd8">內容8</div>
        <div id="cd4">內容4</div>
        <div id="cd7">內容7</div>
        <div id="cd5">內容5</div>
        <div id="cd2">內容2</div>
        <div id="cd6">內容6</div>
        <div id="cd0">內容0</div>
    </div>
    <button onclick="sortDivs()">按 ID 數字排序</button>

    <script>
        function sortDivs() {
            const container = document.getElementById('content');
            // 1. 獲取所有直屬 div 子元素
            const divs = Array.from(container.children).filter(el => el.tagName === 'DIV');
            
            // 2. 排序:提取 ID 中的數字比較
            divs.sort((a, b) => {
                const numA = parseInt(a.id.match(/\d+$/)?.[0] || '0', 10);
                const numB = parseInt(b.id.match(/\d+$/)?.[0] || '0', 10);
                return numA - numB;
            });
            
            // 3. 重新掛載:appendChild 會自動移動現有節點
            divs.forEach(div => container.appendChild(div));
        }
    </script>
</body>
</html>

關鍵技術點解析

技術點代碼說明
獲取子元素container.childrenHTMLCollection,即時集合,轉數組後操作
提取數字id.match(/\d+$/)正則匹配 ID 結尾數字,兼容 cd10、cd100 等多位數
排序divs.sort((a,b) => numA - numB)數值比較,避免字符串比較 '10' < '2'
移動節點container.appendChild(div)對已在文檔中的節點,appendChild 會**移動**而非複製

進階:通用排序工具函數

function sortChildrenByIdNumber(parentId, childTag = 'DIV', idPattern = /(\d+)$/) {
    const parent = document.getElementById(parentId);
    if (!parent) return;
    
    const children = Array.from(parent.children).filter(el => el.tagName === childTag);
    children.sort((a, b) => {
        const matchA = a.id.match(idPattern);
        const matchB = b.id.match(idPattern);
        const numA = matchA ? parseInt(matchA[1], 10) : 0;
        const numB = matchB ? parseInt(matchB[1], 10) : 0;
        return numA - numB;
    });
    children.forEach(el => parent.appendChild(el));
}

// 使用:sortChildrenByIdNumber('content');

總結

JS 排序 DOM 元素核心:**Array.from + 正則提取數字 + sort 數值比較 + appendChild 移動**。這利用了 DOM 節點「同一時刻只能在一個父節點下」的特性,無需創建新節點、無需 innerHTML 重構,效能最優、代碼最簡潔。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved