JavaScript/重構 DOM
外觀
除了新增和刪除節點外,樹上常見的活動是重新排列節點或子樹。在之前的一些示例中,我們已經看到 appendChild 將節點插入到父節點的最後一個子節點中。當然,這不是侷限於當前建立的子節點。對於現有節點,也可以執行相同的操作。因此,它是執行重新排列的適當函式。
我們使用以下示例 HTML 頁面來演示各種可能性。
<!DOCTYPE html>
<html>
<head>
<script>
function show() {
"use strict";
// ...
}
</script>
</head>
<body id="body" style="margin:2em">
<h1>The magic manipulator</h1>
<button id="buttonShow" onclick="show()" style="margin:1em 0em 1em 0em">Start</button>
<div id="div_1">Our sweet products
<ul id="ul_1">
<li id="li_11">Ice creme</li>
<li id="li_12">Chocolate</li>
<li id="li_13">Coffee</li>
</ul>
</div>
<div id="div_2">Additional offers
<ul id="ul_2">
<li id="li_21">Creme</li>
<li id="li_22">Sugar</li>
<li id="li_23">Cakes</li>
</ul>
</div>
</body>
</html>
我們識別兩個元素並將它們移動到另一個節點的末尾。這個其他節點不一定是原來的父節點。但是移動後,它就成為新的父節點。
function show() {
"use strict";
// select the first <ul> as the new parent
const ul_1 = document.getElementById("ul_1");
// select two <li> elements to get moved
const li_11 = document.getElementById("li_11");
const li_23 = document.getElementById("li_23"); // The 'cakes'
// move the two children
ul_1.appendChild(li_11);
ul_1.appendChild(li_23);
}
如您所見,“冰淇淋”被移動到其產品組的末尾(暫時)。之後,“蛋糕”是第二個產品組的子節點,被移動到第一個產品組的末尾。
您可以將元素移動到一組兄弟節點中的任何位置。(“兄弟節點”是具有相同父節點的節點。)首先,您必須找到父節點。接下來,您找到子節點,該子節點將成為元素的新後繼節點。當這兩個節點都已知時,函式 insertBefore 將元素插入到此位置。
例如,我們將“蛋糕”移動到第一個產品組的第一位。
function show() {
"use strict";
// select the first <ul> element; it acts as the parent
const ul_1 = document.getElementById("ul_1");
// select the first li element; we need it for positioning
const li_11 = document.getElementById("li_11");
// select 'Cakes' li element
const li_23 = document.getElementById("li_23");
// move the 'Cakes' to the first place of the first product group
ul_1.insertBefore(li_23, li_11);
}
這裡,“蛋糕”成為第一個產品組的第一個元素。使用相同的命令,您可以將它們移動到兄弟節點序列中的任何位置。只需找到將成為其新後繼節點的兄弟節點,而不是“li_11”。
元素中的屬性順序與屬性順序無關。因此,不需要也不需要重新排列它們。當 DOM 被序列化時,程式可能以不同的方式進行(原始順序、按字母順序等)。