我們可以透過 JavaScript 動態地改變 HTML 中的元素,最常見的莫過於動態新增與刪除節點。
向 HTML 中新增元素
首先需要建立一個標籤,接著向該標籤中加入相應內容,最後把建立好的標籤放到目標位置。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>測試文檔</title>
<script type="text/javascript">
function add(){
var element = document.createElement("p");
var node = document.createTextNode("添加新段落");
element.appendChild(node);
x = document.getElementById("demo");
x.appendChild(element);
}
</script>
</head>
<body>
<div id="demo">
<p>這是第一段</p>
</div>
<input type="button" value="按鈕" onclick="add()" />
</body>
</html>
刪除 HTML 中的某個元素
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>測試文檔</title>
<script type="text/javascript">
function deleteE(){
var father = document.getElementById("demo");
var child = document.getElementById("p1");
father.removeChild(child);
}
</script>
</head>
<body>
<div id="demo">
<p id="p1">這是第一段</p>
<p id="p2">這是第二段</p>
</div>
<input type="button" value="刪除" onclick="deleteE()" />
</body>
</html>
新增元素時使用 createElement 搭配 appendChild,刪除元素則透過父節點呼叫 removeChild,這兩者是動態操作 DOM 最基礎也最常用的做法。