DOM 操作是所有前端基本功裡最容易被低估的一塊。這篇透過兩個可運行的小範例,把 removeChild、createElement 與 createAttribute 這幾個核心方法串起來,順便示範怎麼觀察一個節點的狀態。
<body>
<p id="p1">welcome to <b>javascript</b> world !</p>
<script language="javascript" type="text/javascript">
<!--
function nodestatus(node) {
var temp = "";
if (node.nodeName != null) {
temp += "nodeName=" + node.nodeName + "\n";
} else temp += "nodeName=null \n";
if (node.nodeType != null) {
temp += "nodeType=" + node.nodeType + "\n";
} else temp += "nodeType=null \n";
if (node.nodeValue != null) {
temp += "nodeValue=" + node.nodeValue + "\n";
} else temp += "nodeValue=null \n";
return temp;
}
var parent = document.getElementById("p1");
var msg = "父節點 \n" + nodestatus(parent) + "\n";
// 取得 p 元素的最後一個子節點
last = parent.lastChild;
msg += "刪除之前:lastChild-- " + nodestatus(last) + "\n";
// 刪除 p 的最後一個子節點,此時 lastChild 會變成 b 元素
parent.removeChild(last);
last = parent.lastChild;
msg += "刪除之後:lastChild-- " + nodestatus(last) + "\n";
alert(msg);
-->
</script>
</body>
這個範例的用意是示範一個常被忽略的細節:lastChild 取到的不一定是元素節點,標籤之間的空白與換行也會被視為文字節點。所以在這個例子中,第一次取到的其實是 b 之後的文字節點,刪掉之後 lastChild 才變成 b 元素。想只針對元素操作時,建議改用 children 集合。
<html>
<head>
<title>js 控制新增、刪除節點</title>
</head>
<script type="text/javascript">
var all;
function addParagraph() {
all = document.getElementById("paragraphs").childNodes;
var newElement = document.createElement("p");
var seq = all.length + 1;
// 建立新的 id 屬性
var newAttr = document.createAttribute("id");
newAttr.nodeValue = "p" + seq;
newElement.setAttribute(newAttr);
// 建立文字內容節點
var txtNode = document.createTextNode("段落" + seq);
// 把文字掛到新段落上,再把整段落掛進容器
newElement.appendChild(txtNode);
document.getElementById("paragraphs").appendChild(newElement);
}
function delParagraph() {
all = document.getElementById("paragraphs").childNodes;
document.getElementById("paragraphs").removeChild(all[all.length - 1]);
}
</script>
<style>
p { background-color: #e6e6e6; }
</style>
<body>
<center>
<input type="button" value="新增節點" onclick="addParagraph();"/>
<input type="button" value="刪除節點" onclick="delParagraph();"/>
<div id="paragraphs">
<p id="p1">段落1</p>
<p id="p2">段落2</p>
</div>
</center>
</body>
</html>
新增節點基本上是固定四步:用 createElement 造元素、用 createAttribute 或 setAttribute 設屬性、用 createTextNode 造文字,最後用 appendChild 把子節點與父節點接起來。
刪除則是兩步:先取得目標節點,再呼叫其父節點的 removeChild。
順帶一提,appendChild 有個特性常被拿來當作移動節點的技巧:如果傳入的節點已經在 DOM 上,它會被搬過去而不是複製,這在調整元素順序時很好用。
以上就是 JS 操作 DOM 新增與刪除節點的實作分享,希望對你的學習有所幫助。