將無序的 <div id="cd3">...</div> 等元素,按 ID 中的數字(0-9)升序重新排列到父容器中。
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.children | HTMLCollection,即時集合,轉數組後操作 |
| 提取數字 | 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 重構,效能最優、代碼最簡潔。